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

Col*_*las 2 cocoa singleton cocoa-touch memory-management properties

假设我有一个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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • @property (strong, readwrite) MySingleton * mySingleton

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

CRD*_*CRD 6

weak只有当被引用的对象可以被释放时才有用,如果你sharedInstance不会这样做 - 对象被创建一次然后在应用期间生存.所以坚持strong这里(你也可以使用,assign因为你知道这样做是安全的,但没有强有力的理由这样做,这可能会令人困惑).