objective-c - 如何避免通过[[alloc] init]创建iOS单例类
大家讲道理
大家讲道理 2017-04-18 09:41:01
0
6
716

网站普遍的创建单例类的方法有下面两种:

+ (instancetype)sharedManager {
    static id _sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });
    return _sharedInstance;
}
+ (instancetype)sharedManager {
    static id _sharedInstance = nil;
    @synchronized(self) {
        if (_sharedInstance == nil)
            _sharedInstance = [[self alloc] init];
    }
    return _sharedInstance;
}

但是该如何避免意外的用[[alloc] init]创建呢?主要是发现网上找到的大多仅仅只有上面的代码,少有考虑被init或者copy的情况

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回覆(6)
Ty80

http://www.jianshu.com/p/08b1...
看看這篇我的寫部落格.

黄舟

又去stackovweflow找了下方法,我覺得既然是單例模式,呼叫者就應該嚴格按照單例的要求,透過統一的介面(這裡是sharedInstance)去創建單例,而不應該出現呼叫[[class alloc] init]也能成功創建單例的情況,如果出現[[class alloc] init]的情況,我覺得更應該讓Xcode給出警告不能用此方法

- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
PHPzhong

額外創建有很多,還有new方法也可以,把這些方面都重載一遍回傳 sharedManager 實例,或者直接拋出異常

迷茫

覆蓋allocWithZone和copyWithZone方法。
因為透過alloc或copy還是new,都是透過呼叫allocWithzone和copyWithzone來分配空間的。
你可以把sharedManager 方法裡面的程式碼寫到這兩個方法裡面,就可以從根本實作了單例的情況

大家讲道理
  • (instancetype)init {
    @throw [NSException異常WithName:@"停用"原因:@"請使用init代替..." userInfo:nil];
    return self;
    }

🎜🎜
Peter_Zhu

這樣寫就可以了

static Singleton *slt = nil;

+ (instancetype)sharedInstance{
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
       slt = [[self alloc]init];
   });
   return slt;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
       slt = [super allocWithZone:zone];
      
   });
   return slt;
}

- (id)copyWithZone:(NSZone *)zone
{
   return slt;
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!