Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a singleton with allocWithZone:

BNRItemStore is a singleton, and I was confused on why super allocWithZone: must be called instead of plain old super alloc. And then override alloc instead of allocWithZone.

#import "BNRItemStore.h"

@implementation BNRItemStore

+(BNRItemStore *)sharedStore {
    static BNRItemStore *sharedStore = nil;

    if (!sharedStore)
        sharedStore = [[super allocWithZone: nil] init];

    return sharedStore;
}

+(id)allocWithZone:(NSZone *)zone {
    return [self sharedStore];
}

@end
like image 431
stumped Avatar asked Aug 15 '12 01:08

stumped


2 Answers

[super alloc] will call through to allocWithZone:, which you've overridden to do something else. In order to actually get the superclass's implementation of allocWithZone: (which is what you want there) rather than the overridden version, you must send allocWithZone: explicitly.

The super keyword represents the same object as self; it just tells the method dispatch mechanism to start looking for the corresponding method in the superclass rather than the current class.

Thus, [super alloc] would go up to the superclass, and get the implementation there, which looks something like:

+ (id) alloc
{
    return [self allocWithZone:NULL];
}

Here, self still represents your custom class, and thus, your overridden allocWithZone: is run, which will send your program into an infinite loop.

like image 193
jscs Avatar answered Nov 12 '22 08:11

jscs


From Apple's documentation:

This method exists for historical reasons; memory zones are no longer used by Objective-C.

like image 36
Rivera Avatar answered Nov 12 '22 07:11

Rivera