# 介紹1、官方文檔寫法```objcstatic AccountManager *DefaultManager = nil; + (AccountManager *)defaultManager { if (!DefaultManager) DefaultManager = [[self allo... ...
介紹
1、官方文檔寫法
static AccountManager *DefaultManager = nil;
+ (AccountManager *)defaultManager {
if (!DefaultManager) DefaultManager = [[self allocWithZone:NULL] init];
return DefaultManager;
}
2、來自 objcolumnist
+ (AccountManager *)sharedManager
{
static AccountManager *sharedAccountManagerInstance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
sharedAccountManagerInstance = [[self alloc] init];
});
return sharedAccountManagerInstance;
}
該寫法滿足三個特性:
1)線程安全。
2)滿足靜態分析器的要求。
3)相容了ARC
樣例
@interface BmobIMNetwork ()<GCDAsyncSocketDelegate>
@property (strong, nonatomic) GCDAsyncSocket *gcdAsyncSocket;
@property (strong, nonatomic) NSMutableData *packet;
@end
@implementation BmobIMNetwork
+ (BmobIMNetwork *)sharedBmobIMNetwork
{
static BmobIMNetwork *sharedBmobIMNetworkInstance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
sharedBmobIMNetworkInstance = [[self alloc] initPritate];
});
return sharedBmobIMNetworkInstance;
}
- (instancetype)initPritate{
self = [super init];
if (self) {
_gcdAsyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
_packet = [[NSData alloc] init];
}
return self;
}
- (instancetype)init{
@throw [[NSException alloc] initWithName:@"Singleton" reason:@"Use + [BmobIMNetwork sharedBmobIMNetwork]" userInfo:nil];
return nil;
}