IOS中如何实现单例
这篇文章主要介绍了IOS中如何实现单例,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
为路南等地区用户提供了全套网页设计制作服务,及路南网站建设行业解决方案。主营业务为网站设计制作、成都做网站、路南网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
详解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@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
感谢你能够认真阅读完这篇文章,希望小编分享的“IOS中如何实现单例”这篇文章对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联行业资讯频道,更多相关知识等着你来学习!
网页题目:IOS中如何实现单例
当前路径:http://ybzwz.com/article/jegdid.html