簡體   English   中英

Objective-C中的單例混淆

[英]Singleton confusion in Objective-C

考慮以下代碼:

+(id)sharedInstance
{
    static dispatch_once_t pred;
    static MyClass *sharedInstance = nil;
    dispatch_once(&pred, ^{
        sharedInstance = [[MyClass alloc] init];
    });
    return sharedInstance;
}

如果遵循這種單例設計模式,則可以做出以下假設:

  • 借助GCD,分配和初始化將僅執行一次。
  • 只能從此實現中訪問sharedInstance類變量,並且無論實例如何,都可以在該類之間共享。

第一次創建實例時,我將執行以下操作:

MyClass *something = [MyClass sharedInstance];

我的問題是,如果我再次調用預覽代碼,但是像這樣:

MyClass *somethingOther = [MyClass sharedInstance];

我只能想到一個結果。

結果:

static MyClass *sharedInstance = nil;

使sharedInstance類變量指向nil並返回nil,所以somethingOther將為nil。

但是我認為應該在單例中發生的事情是改為返回共享實例。

現在考慮以下代碼:

+ (MotionManagerSingleton*)sharedInstance {

    static MotionManagerSingleton *_sharedInstance;
    if(!_sharedInstance) {
        static dispatch_once_t oncePredicate;
        dispatch_once(&oncePredicate, ^{
            _sharedInstance = [[super allocWithZone:nil] init];
            });
    }

    return _sharedInstance;
}

+ (id)allocWithZone:(NSZone *)zone {    

    return [self sharedInstance];
}

- (id)copyWithZone:(NSZone *)zone {
    return self;    
}

在這里

static MotionManagerSingleton *_sharedInstance;

不會將我的變量設置為nil,但我認為默認情況下所有對象指針都初始化為nil。

我的問題是,這些類方法如何返回“ sharedInstance”?

謝謝

一。 未初始化的指針是未初始化的。

static MotionManagerSingleton *_sharedInstance;

不會使您的MotionManagerSingleton指向nil 它將指向一個未定義的(垃圾)位置。

二。 聲明為static變量僅初始化一次(是的,語法與語義有點不一致),因此您的第一個實現不會使返回的共享實例無效。 那是一個完美的實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM