【发布时间】:2013-09-10 16:41:26
【问题描述】:
我正在关注关于 iOS 编程的 Big Nerd Ranch 书籍。
有一个静态类的示例:
#import <Foundation/Foundation.h>
@interface BNRItemStore : NSObject
+ (BNRItemStore *) sharedStore;
@end
我在理解下面的 cmets 中带有问号的位时遇到了问题。
如果我尝试分配这个类,覆盖的方法会将我带到sharedStore,这反过来又将静态指针sharedStore 设置为nil。由于指针不存在,条件after会第一次命中。
这个想法是我第二次在同一个地方,它不会分配一个新的实例,而是获取现有的实例。但是对于static BNRItemStore *sharedStore = nil;,我将指针设置为 nil 并销毁它,不是吗?因此,每次我无意中创建一个新实例时,不是吗?
#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
【问题讨论】:
-
您拥有的是所谓的“单例”模式。最令人困惑的部分是,以
static开头的语句不是作为封闭方法的一部分执行的,而是仅在类加载时执行一次。 -
(我希望这本书实际上并没有将其称为“静态类”。)