//
//? SoundTools.m
//? 02-單例(ARC)
//
//? Created by apple on 14-8-24.
//? Copyright (c) 2014年apple. All rights reserved.
//
#import"SoundTools.h"
/**
單例小結:
1.創建一個靜態的實例對象,在靜態區保存唯一的副本
2.創建一個sharedXXX類方法,方便全局統一條用
3.重寫allocWithZone方法
如果是面試,寫上面三步就夠了
4. copyWithZone方法
*/
@implementationSoundTools
staticSoundTools*_instance;
/**是為當前對象分配內存空間,所有方法都會最終調用的方法*/
/**
無論如何實例化,在內存中都最多保留一個副本,對象應該保存在靜態區
靜態區中的對象,是在整個程序結束后,才會被銷毀。
*/
+ (id)allocWithZone:(struct_NSZone*)zone
{
//??? return nil;
//懶加載,不能保證多線程并發的實例化是唯一的
//加互斥鎖,性能非常糟糕。蘋果強烈不建議程序員使用!
//??? @synchronized(self) {
//??????? if (_instance == nil) {
//??????????? _instance = [super allocWithZone:zone];
//??????? }
//??? }
// dispatch_once能夠確保塊代碼中的操作只被執行一次
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
// block中的代碼只能被執行一次
_instance= [superallocWithZone:zone];
});
return_instance;
}
+ (instancetype)sharedSoundTools
{
//無論調用多少次類方法,對象只會被初始化一次
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
_instance= [[selfalloc]init];
});
return_instance;
}
- (id)copyWithZone:(NSZone*)zone
{
return_instance;
}
#pragma mark - MRC相關方法
//判斷是否支持MRC
#if !__has_feature(objc_arc)
- (onewayvoid)release {}
- (id)retain {return_instance; }
- (id)autorelease {return_instance; }
- (NSUInteger)retainCount {returnUINT_MAX; }
#endif
- (id)init
{
self= [superinit];
if(self) {
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
//對象屬性的初始化
self.num=100;
NSLog(@"初始化了- %d",self.num);
});
}
returnself;
}
- (void)playSoundWithName:(NSString*)name
{
NSLog(@"播放聲音%@", name);
}
@end