簡體   English   中英

多線程如何在Objective-C中工作?

[英]How does multithread work in objective-c?

在啟動線程的情況下,我仍可以訪問父線程上的方法嗎? 有沒有一種特定的方法來調用此方法? 如果是這樣,那是什么?

注意:在我的場景中,這兩個線程都是用於數據操作的,它們不是與接口相關的線程(我知道這是在.NET中考慮的,不知道它們在Objective-c中)。

在這種情況下,最好使用Grand Central Dispatch(GCD),而不是直接使用NSThead或NSOperation。

並發概述: http : //developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008091

大中央調度簡介: http : //cocoasamurai.blogspot.com/2009/09/guide-to-blocks-grand-central-dispatch.html

在您的示例中,可以使用對Grand Central Dispatch的嵌套調用來實現此功能:

dispatch_queue_t backgroundQueue = dispatch_queue_create("com.example.exampleQueue", 0);

dispatch_async(backgroundQueue, ^{

    // operate on data in the background here
    NSData *stuff = [self doSomethingComplex];

    dispatch_async(dispatch_get_main_queue(), ^{
    // Perform Task back in the main thread
        [viewController updateStuff:stuff];
    });
});

此方法是執行此類任務的首選方法。 此外,通過利用塊,一目了然地理解代碼也很容易,而不必在類中舉例說明多個方法。

根據定義,線程共享父線程的狀態。 在ObjectiveC中,如果您產生一個工作線程並想在主線程上調用某個方法,則可以像這樣進行:

[self performSelectorOnMainThread:@selector(someMethod:) withObject:nil waitUntilDone:NO];

如果它們不是接口東西,或者可能導致某些接口東西可以調用,則可以只調用然后,然后以任何語言執行必須執行的任何常規線程安全性操作,例如@syschronise(obj)NSLock 但是,如果是會導致接口問題的東西,那么您將必須像'Srikar'那樣寫[self performSelectorOnMainThread:@selector(setDataCount:) withObject:count waitUntilDone:NO]; 它將有效地將消息放置到NSRunLoop提示上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM