你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS 如何創建單例

iOS 如何創建單例

編輯:IOS開發綜合
// YOURCLASSNAME.h

@interface YOURCLASSNAME : NSObject

+(instancetype) sharedInstance;

@end


// YOURCLASSNAME.m

@implementation YOURCLASSNAME

+ (instancetype)sharedXXX {
    static YOURCLASSNAME *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        // alloc & init work
       // [[YOURCLASSNAME alloc] init];
    });

    return _sharedInstance;
}

@end

一個具體的例子如下:(from AFNetWorking framework -> AFNetworkActivityIndicatorManager)

+ (instancetype)sharedManager {
    static AFNetworkActivityIndicatorManager *_sharedManager = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedManager = [[self alloc] init];
    });

    return _sharedManager;
}




  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved