简体   繁体   English

iPhone SDK后台线程调用其他方法

[英]iPhone SDK Background threads calling other methods

I am a seemingly straightforward question that I can't seem to find an answer to (and it is hindering my app). 我是一个看似简单的问题,似乎无法找到答案(这阻碍了我的应用程序)。

I have a background thread running a paricular method: 我有一个运行特定方法的后台线程:

-(void)processImage:(UIImage *)image {

  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

  //Process image here in the background here

  [pool drain];
}

This much works great, but my question comes when I want to call another method from inside the already-background method. 这很好用,但是当我想从已经后台的方法中调用另一个方法时,我的问题就来了。 Does this call stay in the background? 此通话是否保留在后台? Do I need to add NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 我是否需要添加NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; and [pool drain]; [pool drain]; to the new method to make it run in the background as well? 使新方法也可以在后台运行?

Any advice would be very helpful. 任何建议都将非常有帮助。 I am a bit confused about this. 我对此有些困惑。

Many thanks, Brett 非常感谢,布雷特

It WILL stay in the background, on the same thread it was called from. 它会留在后台,与它被调用的线程相同。

Some threading notes to consider with this: 需要考虑的一些线程注意事项:

  • It may not be obvious, but if you call a timer from the background thread, and the thread exits before the timer is supposed to go off, the timer will NOT be called. 可能并不明显,但是如果您从后台线程调用计时器,并且该线程在应该关闭计时器之前退出,则不会调用该计时器。 Thus it is recommended you setup timers from the main thread 因此,建议您从主线程设置计时器
  • You dont need another autorelease pool unless you spawn another thread. 除非生成另一个线程,否则不需要另一个自动释放池。
  • Any UI updates should be done on the main thread 任何UI更新都应在主线程上完成

You don't need to add yet another autorelease pool, the one you already have is enough. 您不需要添加另一个自动释放池,您已经拥有的就足够了。 And yes, all calls that you make that originate from that thread stay in that thread and thus also run "in the background". 是的,您从该线程发起的所有调用都保留在该线程中,因此也“在后台”运行。 Exception would be the use of "performSelectorOnMainThread:", which of course makes the given selector to be performed on the main thread :-) If you want to call GUI methods (like setting the image on an UIImageView) you should make sure to do so on the main thread. 例外是使用“ performSelectorOnMainThread:”,这当然会使给定的选择器在主线程上执行:-)如果要调用GUI方法(例如在UIImageView上设置图像),则应确保执行所以在主线程上。 See the docs for "performSelectorOnMainThread:waitUntilDone:" (sorry for not giving you you the links, am typing this on my iPad). 请参阅有关“ performSelectorOnMainThread:waitUntilDone:”的文档(很抱歉,没有给您提供链接,请在我的iPad上输入此链接)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM