IOS開發(64)之GCD任務最多隻執行一次

來源:互聯網
上載者:User
1 前言

 

使用 dispatch_once 函數 在 APP 的生命週期內來保證你想確保每段代碼只執行一次,即使它在代碼的不同地方多次調用(比如單例的初始化)。

 

2 代碼執行個體

ZYAppDelegate.m

 

//一個用於調度一次函數的標識static dispatch_once_t onceToken;//Block Objectvoid (^executedOnlyOnce)(void) = ^{    static NSUInteger numberOfEntries = 0;    numberOfEntries++;    NSLog(@"Executed %lu time(s)", (unsigned long)numberOfEntries);};- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    //聲明一個隊列    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    //執行一次的隊列    dispatch_once(&onceToken, ^{ dispatch_async(concurrentQueue,                                                executedOnlyOnce);    });    dispatch_once(&onceToken, ^{ dispatch_async(concurrentQueue,                                                executedOnlyOnce);    });    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];    // Override point for customization after application launch.    self.viewController = [[[ZYViewController alloc] initWithNibName:@"ZYViewController" bundle:nil] autorelease];    self.window.rootViewController = self.viewController;    [self.window makeKeyAndVisible];    return YES;}

 

ZYViewController.m

 

- (void)viewDidLoad{    [super viewDidLoad];    ZYMySingleton *test = [[ZYMySingleton alloc] init];    //迴圈單例方法    for (int i=0; i<5; i++) {        [test sharedInstance];    }    [test release];}

 

ZYMySingleton.m

 

- (id) sharedInstance{    static ZYMySingleton *SharedInstance = nil;    //一個用於調度一次函數的標識    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        SharedInstance = [ZYMySingleton new];        NSLog(@"SharedInstance is ======>%@",SharedInstance);    });    return SharedInstance;}

 

運行後控制台顯示結果

 

2013-05-10 17:30:49.334 GCDSingleTest[2717:1303] Executed 1 time(s)

2013-05-10 17:30:49.336 GCDSingleTest[2717:c07] SharedInstance is ======><ZYMySingleton: 0x7195990>

3 結語

以上是所有內容,希望對大家有所協助

Demo代碼下載:http://download.csdn.net/detail/u010013695/5353668

相關文章

聯繫我們

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