Cocoa touch @指向单例(或sharedInstance)的属性:强或弱,为什么?

Cocoa touch @指向单例(或sharedInstance)的属性:强或弱,为什么?,cocoa-touch,cocoa,memory-management,properties,singleton,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]

假设我有一个
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;
}
那么,在引用此对象的类中,我应该做什么(为什么要这样做):

  • @属性(强,读写)MySingleton*MySingleton

  • 或者:
    @property(弱,读写)MySingleton*MySingleton


仅在引用的对象可以解除分配的情况下才有用,在您的
共享状态
的情况下,这不会发生-对象只创建一次,然后在应用期间有效。因此,请坚持使用这里的
strong
(您也可以使用
assign
,因为您知道这样做是安全的,但是没有充分的理由这样做,这可能会让人困惑)。

为什么会让人困惑?因为没有理由使用它,而且它可能会释放共享实例。