iOS開發中單例對象的標準建立方法

來源:互聯網
上載者:User

標籤: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.未完待續  明天補上

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.