我又在读一本书,并且有这样的类实现:
@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
我觉得奇怪的是,在类之外的任何地方,例如其他类,都是被调用的init
方法。BNRItemStore
然而,它仍然以某种方式被调用,即使有人在BNRItemStore
类外键入了这样的代码:
[[BNRItemStore sharedStore] createItem]; // This still calls the init method of BNRItemStore. How?
有人可以解释为什么吗?