详解IOS 单例的两种方式
程序员文章站
2023-12-18 15:03:52
详解ios 单例的两种方式
方法一:
#pragma mark -
#pragma mark sharedsingleton methods
//...
详解ios 单例的两种方式
方法一:
#pragma mark - #pragma mark sharedsingleton methods //单例函数 static rtdatamodel *sharedsingletonmanager = nil; + (rtdatamodel *)sharedmanager { @synchronized(self) { if (sharedsingletonmanager == nil) { sharedsingletonmanager = [[self alloc] init]; } } return sharedsingletonmanager; } + (id)allocwithzone:(nszone *)zone { @synchronized(self) { if (sharedsingletonmanager == nil) { sharedsingletonmanager = [super allocwithzone:zone]; return sharedsingletonmanager; // assignment and return on first allocation } } return nil; //on subsequent allocation attempts return nil } - (id)copywithzone:(nszone *)zone { return sharedsingletonmanager; } - (id)retain { return sharedsingletonmanager; } - (nsuinteger)retaincount { return uint_max; //denotes an object that cannot be released } - (oneway void)release { //do nothing } - (id)autorelease { return sharedsingletonmanager; } //单例函数结束
方法二:
.h文件
#import <foundation/foundation.h> @interface rttestdatamodel : nsobject { nsmutablearray * _buydatatarray; nsmutablearray * _selldatatarray; } + (rttestdatamodel *)sharedmanager; - (void)addoptionbuydataarraymodel: (nsmutablearray *)dataarray; - (nsmutablearray *)getoptionbuydataarraymodel; @end
.m文件
#import "rttestdatamodel.h" @implementation rttestdatamodel + (rttestdatamodel *)sharedmanager { static rttestdatamodel *sharedmanager = nil; static dispatch_once_t predicate; dispatch_once(&predicate,^{ sharedmanager = [[rttestdatamodel alloc]init]; }); return sharedmanager; } - (void)dealloc { [_buydatatarray removeallobjects]; [_buydatatarray release]; [super dealloc]; } - (id)init { self = [super init]; if (self != nil) { _buydatatarray = [[nsmutablearray alloc] initwithcapacity:8]; } return self; } - (void)addoptionbuydataarraymodel: (nsmutablearray *)dataarray{ if (dataarray != nil) { [_buydatatarray removeallobjects]; [_buydatatarray addobjectsfromarray:dataarray]; } } - (nsmutablearray *)getoptionbuydataarraymodel{ return _buydatatarray; } @end
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!