IOS单例
#import <Foundation/Foundation.h> @interface FuCardSettings : NSObject + (FuCardSettings *)sharedInstance ; @end
#import "FuCardSettings.h" @implementation FuCardSettings //================= 单例 ============== start static FuCardSettings *sharedSettings = nil; + (FuCardSettings *)sharedInstance { if(sharedSettings == nil){ sharedSettings = [[[self alloc] init]autorelease]; } return sharedSettings; } + (id)allocWithZone:(NSZone *)zone { @synchronized(self) { if (sharedSettings == nil) { sharedSettings = [super allocWithZone:zone]; } } return sharedSettings; } + (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (NSUInteger)retainCount { return NSUIntegerMax; } - (oneway void)release { } - (id)autorelease { return self; } //================= 单例 ============== end @end
上面是传统的单例:
还有一种用GCD实现的单例:
#import <Foundation/Foundation.h> @interface Tool1 : NSObject @property(nonatomic,copy)NSString *test; + (instancetype)instance; @end @implementation Tool1 + (instancetype)instance { static Tool1* tool; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ tool = [[Tool1 alloc] init]; }); return tool; } - (instancetype)init { self = [super init]; if (self) { _test = @"test"; } return self; } @end
该写法具有以下几个特性:
1. 线程安全。
2. 满足静态分析器的要求。
3. 兼容了ARC
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。