Reputation: 495
again I am reading a book and there is such implementation of class:
@implementation BNRItemStore
// Init method
- (id)init
{
self = [super init];
if(self)
{
allItems = [[NSMutableArray alloc] init];
}
return self;
}
#pragma mark singleton stuff
// Implementing singleton functionality
+(BNRItemStore*) sharedStore
{
static BNRItemStore *sharedStore = nil;
// Check if instance of this class has already been created via sharedStore
if(!sharedStore)
{
// No, create one
sharedStore = [[super allocWithZone:nil] init];
}
return sharedStore;
}
// This method gets called by alloc
+ (id)allocWithZone:(NSZone *)zone
{
return [self sharedStore];
}
#pragma mark Methods
// return pointer to allItems
-(NSArray*) allItems
{
return allItems;
}
// Create a random item and add it to the array. Also return it.
-(BNRItem*) createItem
{
BNRItem *p = [BNRItem randomItem];
[allItems addObject:p];
return p;
}
@end
The thing I find strange is that Nowhere outside the class, e.g., some other class, is the init
method of BNRItemStore
called. However, still by some means it gets called, even when someone has typed such code outside the BNRItemStore
class:
[[BNRItemStore sharedStore] createItem]; // This still calls the init method of BNRItemStore. How?
Can someone please explain why?
Upvotes: 1
Views: 157
Reputation: 5473
-init
gets called because +sharedStore
calls it:
sharedStore = [[super allocWithZone:nil] init];
[super allocWithZone:nil]
skips the current class' implementation of allocWithZone and calls the superclass implementation. However, init is an ordinary method call so it doesn't skip the superclass implementation.
Although the quoted line makes it look like super is an object that you're sending a message to, it really means something like "self, but skip the current class' implementation and use the superclass instead". It doesn't affect messages sent to the returned object.
Upvotes: 0
Reputation: 8147
sharedStore = [[super allocWithZone:nil] init];
This line is responsible for the init
call. First time entering sharedStore
the sharedStore
variable is nil
, so the condition check fails and an instance of the class is initialized.
Upvotes: 1