iOS单例设计 MRC&ARC

单例设计思想是iOS开发中常见的设计思想之一,下面总结出MRC&ARC环境下单例代码实现:

#import

@interface AccountManager : NSObject < NSCopying >

+ (
instancetype )sharedAccountManager;

@end


#import "AccountManager.h"

@implementation AccountManager

static AccountManager *instance;

#if __has_feature(objc_arc)
//  MAEK:在ARC中需要重写以下方法

+ (
instancetype )sharedAccountManager
{
   
static dispatch_once_t onceToken;
   
dispatch_once (&onceToken, ^{
       
instance = [[ AccountManager alloc ] init ];
    });
   
   
return instance ;
}

+ (
instancetype )allocWithZone:( struct _NSZone *)zone
{
   
static dispatch_once_t onceToken;
   
dispatch_once (&onceToken, ^{
       
instance = [ super allocWithZone :zone];
    });
   
   
return instance ;
}

- (
id )copyWithZone:( NSZone *)zone
{
   
return instance ;
}

#else
// MAEK:在MRC中除了要重写上面的方法以外还要重写以下方法

+ (
instancetype )sharedAccountManager
{
   
static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[AccountManager alloc] init];
    });
   
   
return instance;
}

+ (
instancetype )allocWithZone:( struct _NSZone *)zone
{
   
static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [
super allocWithZone:zone];
    });
   
   
return instance;
}

- (
id )copyWithZone:(NSZone *)zone
{
   
return instance;
}

- (
oneway void )release
{
   
// 什么都不做
}

- (
instancetype )retain
{
   
return instance;
}

- (
instancetype )autorelease
{
   
return instance;
}

/// 永远保证引用计数为 1
- (NSUInteger)retainCount
{
   
return 1 ;
}

#endif

@end

你可能感兴趣的:(iOS单例设计 MRC&ARC)