標籤:style blog class c code java
//標準的單例寫法
//以建立歌曲的管理者為例進行建立。
+(instancetype) sharedQYSongManager{ static QYSongsManager *songManager =nil;
//採用GDC標準單例實現方法 static dispatch_once_t onceToken; //Executes a block object once and only once for the lifetime of an application. dispatch_once(&onceToken,^{ songManager =[[self alloc] init]; }); return songManager;}
建立完成後songManager即為單例的對象,即在記憶體中不管alloc多少個對象都是指的是同一個對象。
有幾點需要說明:
1.instancetype是什嗎?
蘋果官方給出的解釋是:Use the instancetype keyword as the return type of methods that return an instance of the class they are called on (or a subclass of that class). These methods include alloc, init, and class factory methods.
//iOS開發:CLang添加了一個新的關鍵字:instancetype;這是一個上下文相關的關鍵字,並只能作為Objective-C方法的傳回型別。使用instancetype可讓編譯器準確推斷返回的具體類型,把一些運行時的錯誤在編譯時間暴露出來
下面我們來看一個蘋果官方給出的例子
@interface MyObject : NSObject+ (instancetype)factoryMethodA;+ (id)factoryMethodB;@end @implementation MyObject+ (instancetype)factoryMethodA { return [[[self class] alloc] init]; }+ (id)factoryMethodB { return [[[self class] alloc] init]; }@end void doSomething() { NSUInteger x, y; x = [[MyObject factoryMethodA] count]; // Return type of +factoryMethodA is taken to be "MyObject *" y = [[MyObject factoryMethodB] count]; // Return type of +factoryMethodB is "id"}
因為+ factoryMethodA的instancetype傳回型別,該訊息運算式的類型是為MyObject*。由於MyObject來沒有一個計數方法,編譯器給出了一個關於x行警告:
main.m: ’MyObject’ may not respond to ‘count’
2.未完待續 明天補上