ARC和MRC 兼容的單例模式

1、ARC下的單例實現

  說明:在用戶實例化的方法控制單次執行,同時開放單例的初始化方法。spa

複製代碼
-(instancetype)init{

    self=[super init];
    if(self){
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
        });
    }
    return self;
    

}

static id instance; 
+(instancetype)allocWithZone:(struct _NSZone *)zone{ 
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{ 
    instance=[super allocWithZone:zone]; 
    }); 
return instance;
} 
 
 
+ (instancetype) shareAudio{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{ 
    instance=[[self alloc]init]; 
    }); 
    return instance; 
} 
 
+(id)copyWithZone:(struct _NSZone *)zone{ 
    return instance;
}
複製代碼
2、MRC下的單例實現

   說明:在用戶實例化的方法控制單次執行,同時開放單例的初始化方法,因爲當前爲MRC因此須要控制參內存管理的方法單次執行,所以相比ARC須要增長:code

複製代碼
static id instance; 
+(instancetype)allocWithZone:(struct _NSZone *)zone{ 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
        instance=[super allocWithZone:zone]; 
    }); 
    return instance; 
} 
 
 
+ (instancetype) shareAudio{
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
        instance=[[self alloc]init]; 
    }); 
    return instance; 
} 
-(oneway void)release{ 
} 
 
-(instancetype)autorelease{ 
    return instance; 
} 
 
-(instancetype)retain{ 
    return instance; 
} 
 
-(NSUInteger)retainCount{ 
    return 1; 
}
複製代碼
3、兼容MRC 和ARC的宏定義

   說明:爲了方便後期的引用,能夠將單例抽取爲宏定義,鑑於抽取的時候考慮到當前的手動計數和自動計數所以引入條件編譯:blog

複製代碼
#if !__has_feature(objc_arc)
======當前是ARC
#else
======當前是MRC
#endif

代碼:
#define singleton_h(name)  + (instancetype) share##name;


#if !__has_feature(objc_arc)
#define singleton_m(name)\
 static id instance;\
+(instancetype)allocWithZone:(struct _NSZone *)zone{\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
        instance=[super allocWithZone:zone];\
    });\
    return instance;\
}\
\
\
+ (instancetype) share##name{\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
        instance=[[self alloc]init];\
    });\
    return instance;\
}\
-(oneway void)release{\
}\
\
-(instancetype)autorelease{\
    return instance;\
}\
\
-(instancetype)retain{\
    return instance;\
}\
\
+(id)copyWithZone:(struct _NSZone *)zone{\
    return instance;\
}\
-(NSUInteger)retainCount{\
    return 1;\
}

#else

#define singleton_m(name)\
static id instance;\
+(instancetype)allocWithZone:(struct _NSZone *)zone{\
  static dispatch_once_t onceToken;\
  dispatch_once(&onceToken, ^{\
  instance=[super allocWithZone:zone];\
});\
  return instance;\
}\
\
\
+ (instancetype) share##name{\
  static dispatch_once_t onceToken;\
  dispatch_once(&onceToken, ^{\
   instance=[[self alloc]init];\
  });\
  return instance;\
}\
\
+(id)copyWithZone:(struct _NSZone *)zone{\
   return instance;\
}
#endif
複製代碼
4、文件引用

1 在.h文件引用singleton_h(audio);內存

2 在.m文件引用singleton_m(audio);it

相關文章
相關標籤/搜索