【问题标题】:@property pointing to a singleton (or sharedInstance) : strong or weak and why?@property 指向一个单例(或 sharedInstance):强或弱,为什么?
【发布时间】:2014-02-15 03:14:36
【问题描述】:

假设我有一个像这样初始化的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 ?

【问题讨论】:

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


    【解决方案1】:

    weak 仅在可以释放被引用的对象时才有用,在您的 sharedInstance 的情况下,这不会发生 - 该对象被创建一次,然后在应用程序期间存在。所以在这里坚持使用strong(您也可以使用assign,因为您知道这样做是安全的,但没有充分的理由这样做,这可能会造成混淆)。

    【讨论】:

    • 为什么会让人困惑?
    • 因为没有理由使用它,它考虑了共享实例可能被释放的可能性。
    猜你喜欢
    • 1970-01-01
    • 2013-03-07
    • 2019-08-25
    • 2013-05-10
    • 2018-07-04
    • 2014-01-03
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多