首页 > 代码库 > 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;
}




iOS 如何创建单例