ios筆記-單例文字代碼詳解

來源:互聯網
上載者:User

標籤:

單例設計模式是ios開發中幾大設計模式之一,每個項目中必有單例。下面我用文字加代碼的方式講一下單例模式。

1.我們簡單的建立一個單例類

#import <Foundation/Foundation.h>

@interface SingloneTest : NSObject 

+ (id)shareInstance; 

@end

#import "SingloneTest.h" 

@implementation SingloneTest

+ (id)shareInstance

{

    static id shareInstance;  

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        shareInstance = [[NSObject alloc] init];

    });

@end

2.在appdelegate中,這樣寫

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  

     NSLog(@"~~~~%@~~~~~~",[SingloneTest shareInstance]);

    return YES;

}

列印結果:

SingloneDomo[5469:104528] ~~~~<NSObject: 0x7fff32e0d560>~~~~~~

3.在控制器裡再次建立單例類

- (void)viewDidLoad {

    [super viewDidLoad];

    NSLog(@"~~~~%@~~~~~~",[SingloneTest shareInstance]);

}

列印結果:

SingloneDomo[5469:104528] ~~~~<NSObject: 0x7fff32e0d560>~~~~~~

兩次的列印結果相同,證明是一個對象執行個體,所以在整個工程中,單例可以跳過多個控制器,記錄自己的狀態,不需要逐個頁面進行傳值。

有同學問,問什麼這樣建立的單例,在方法執行結束沒有被銷毀呢?因為 static id shareInstance; static把單例對象指標放在了靜態儲存區,使資料持久化,程式開始就進行初始化,且只初始化一次,不隨runtime機制進行銷毀。所以每次調用+ (id)shareInstance; 方法,其實都是取同一個SingloneTest對象。

ios筆記-單例文字代碼詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.