繁体   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