2010-03-10 38 views

回答

7

正如其他人指出的那样,NSObject不存在于任何一个线程中,线程仅在开始执行其方法时才会发挥作用。

我的建议是每次在对象上调用方法时不使用手动线程,而是使用NSOperations和NSOperationQueue。拥有一个NSOperationQueue作为对象的一个​​实例变量,并且调用插入到队列中的对象创建NSOperations上的各种方法。 NSOperationQueue将在后台线程上处理这些操作,避免您需要拥有多次访问方法的所有手动线程管理。

如果你让这个NSOperationQueue的最大并发计数为1,你还可以避免锁定将在后台线程上执行的各种操作之间的对象内的共享资源(当然你仍然需要锁定实例可以从外部访问的变量)。

对于代表或其他对象的回调,我建议使用-performSelectorOnMainThread:withObject:waitUntilDone,这样就不必考虑让这些委托方法线程安全。

查看Concurrency Programming Guide了解更多。

6

当然,您可以使用NSThreadbackgroundObject使用performSelectorOnMainThread:联系代表。

+0

你可以更具体。 – DevDevDev 2010-03-10 19:22:46

+1

@DevDevDev,关于什么?您需要在MyObj方法中创建和使用线程,然后使用'performSelector:'在主线程上调用;你有更具体的问题吗? – 2010-03-10 19:24:49

2

对象不存在线程AFAIK。您发送给对象的函数将始终在您发送它的线程上执行(除非您使用NSThread或performSelectorOnMainThread或沿着这些线的东西)。

1

你需要的是一个NSOperation和一个块/委托参数来通知调用者完成。

看的NSOperation的文档和NSOperationQueues

0

你应该使用GCD

  • WWDC 2011:

    /* 
    * I didn't initalised your object in background, because 
    * because in the most cases you need your object to stick around 
    * and only perfom the time consimung calculations in background 
    */ 
    
    MyObj* backgroundObject = [[MyObj alloc] initInBackground]; 
    ... 
    
    - (void)startBackgroundTask { 
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
         //in a perfectly async non blocking block :-) 
         BOOL result = [backgroundObject computeResult]; 
    
         dispatch_async(dispatch_get_main_queue(), ^{ 
         //post your result, or do something else with your result 
          [[NSNotificationCenter defaultCenter] postNotificationName:"backgroundComputeResultDone" object:[NSNumber numberWithBool:result]]; 
    
          if (result) { 
           //do some stuff 
          } 
         }); 
        }); 
    } 
    

    也许你可以从苹果here这两个视频看看 - 第210场 - 掌握Grand Central Dispatch

  • WWDC 2011 - Session 30 8 - 块和大中央调度实践
相关问题