2011-08-25 113 views
0

我正在为iOS编写一个多线程应用程序。 我是Objective-C的新手,所以在iPhone之前我还没有玩过线程。可可触摸线程问题

通常使用Java的时候,我创建一个线程,并发送“自我”为对象的线程。并从我可以为线程调用主线程。 这是如何在Objective C中完成的?

如何从线程调用主线程?我一直NSNotificationCenter尝试,但我得到一个错误sigbart:/

这是线程的启动方式:

NSArray *extraParams = [NSArray arrayWithObjects:savedUserName, serverInfo, nil];  // Parameters to pass to thread object 

NSThread *myThread = [[NSThread alloc] initWithTarget:statusGetter      // New thread with statusGetter 
              selector:@selector(getStatusFromServer:) // run method in statusGetter 
               object:extraParams];      // parameters passed as arraylist 
[myThread start];                  // Thread started 

activityContainerView.hidden = NO; 
[activityIndicator startAnimating]; 

任何帮助将是巨大的!

回答

1

您通过向主线程的运行循环添加消息来完成此操作。

基金会提供了一些便利这一点,尤其是-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]NSInvocation

使用前者,你可以简单地写类似:

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

的通知可以从辅助线程(通常调用线程)被派遣。

0

虽然这不是直接回答你的问题,我会强烈建议你在Grand Central Dispatch看一看。它通常比尝试直接使用线程的性能更好。

贾斯汀指出的那样,你可以随时通过调用performSelectorOnMainThread,如果你真的太需要执行主线程的功能。

1

您可以使用performSelectorOnMainThread:withObject:waitUntilDone:,或者,如果你的目标的iOS 4及更高版本,大中央调度,它不要求你实现一个方法只与主线程同步:

dispatch_async(dispatch_get_main_queue(),^{ 
    // Do stuff on the main thread here... 
}); 

这通常会使您的代码更易于阅读。