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?