@property指向单例(或sharedInstance):强弱还为什么?

时间:2014-01-24 08:01:41

标签: cocoa-touch cocoa memory-management properties singleton

假设我的sharedInstance已初始化为

+ (MySingleton *)sharedInstance
{
    static TheConstantsPlaceholder *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[TheConstantsPlaceholder alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}

然后,我应该在引用此对象的类中做什么(以及我为什么要这样做):

  • @property (strong, readwrite) MySingleton * mySingleton

  • 或:@property (weak, readwrite) MySingleton * mySingleton

1 个答案:

答案 0 :(得分:5)

weak仅在被引用的对象可以被释放时才有用,如果您的sharedInstance不会发生这种情况 - 对象会被创建一次,然后在应用期间生效。所以坚持使用strong(您也可以使用assign,因为您知道这样做是安全的,但没有充分的理由这样做,这可能会令人困惑。)

相关问题