iOS 如何創建單例 – iPhone手機開發技術文章 iPhone軟體開發教學課程

// 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;
}

發佈留言