亲宝软件园·资讯

展开

IOS 单例 详解IOS 单例的两种方式

人气:0
想了解详解IOS 单例的两种方式的相关内容吗,在本文为您仔细讲解IOS 单例的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:IOS,单例,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 <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 


如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

加载全部内容

相关教程
猜你喜欢
用户评论