dispatch_async 線程分發注意事項.

來源:互聯網
上載者:User
 1 // NOTE:  GameCenter does not guarantee that callback blocks will be execute on the main thread. 2 // As such, your application needs to be very careful in how it handles references to view 3 // controllers.  If a view controller is referenced in a block that executes on a secondary queue, 4 // that view controller may be released (and dealloc'd) outside the main queue.  This is true 5 // even if the actual block is scheduled on the main thread.  In concrete terms, this code 6 // snippet is not safe, even though viewController is dispatching to the main queue: 7 // 8 //    [object doSomethingWithCallback:  ^() 9 //    {10 //        dispatch_async(dispatch_get_main_queue(), ^(void)11 //        {12 //            [viewController doSomething];13 //        });14 //    }];15 //16 // UIKit view controllers should only be accessed on the main thread, so the snippet above may17 // lead to subtle and hard to trace bugs.  Many solutions to this problem exist.  In this sample,18 // I'm bottlenecking everything through  "callDelegateOnMainThread" which calls "callDelegate".19 // Because "callDelegate" is the only method to access the delegate, I can ensure that delegate20 // is not visible in any of my block callbacks.21 22 - (void) callDelegate: (SEL) selector withArg: (id) arg error: (NSError*) err23 {24     assert([NSThread isMainThread]);25     if([delegate respondsToSelector: selector])26     {27         if(arg != NULL)28         {29             [delegate performSelector: selector withObject: arg withObject: err];30         }31         else32         {33             [delegate performSelector: selector withObject: err];34         }35     }36     else37     {38         NSLog(@"Missed Method");39     }40 }41 42 - (void) callDelegateOnMainThread: (SEL) selector withArg: (id) arg error: (NSError*) err43 {44     dispatch_async(dispatch_get_main_queue(), ^(void)45     {46        [self callDelegate: selector withArg: arg error: err];47     });48 }49 50 - (void) authenticateLocalUser51 {52     if([GKLocalPlayer localPlayer].authenticated == NO)53     {54         [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:^(NSError *error)55         {56             [self callDelegateOnMainThread: @selector(processGameCenterAuth:) withArg: NULL error: error];57         }];58     }59 }

聯繫我們

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