如何让NSRunLoop在一个单独的线程中工作? [英] How to make NSRunLoop work inside a separate thread?

查看:137
本文介绍了如何让NSRunLoop在一个单独的线程中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看以下代码:

@interface myObject:NSObject

-(void)function:(id)param;

@end

@implementation myObject

-(void)function:(id)param
{
    NSLog(@"BEFORE");
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:20]];
    NSLog(@"AFTER");
}

@end


int main(int argc, char *argv[])
{
    myObject *object = [[myObject alloc] init];

    [NSThread detachNewThreadSelector:@selector(function:) toTarget:object withObject:nil];

    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

函数方法,但没有20秒暂停。我该怎么做才能使 NSRunLoop 在分离的线程中工作?

The function method is called but there's no 20 seconds pause. What should i do to make NSRunLoop work in a detached thread?

推荐答案

由于您在另一个线程中运行函数:选择器, [NSRunLoop currentRunLoop] 与in中的不同主线程。

Since you are running the function: selector in a different thread, [NSRunLoop currentRunLoop] is not the same as in the main thread.

请参阅 NSRunLoop参考


如果没有输入源或定时器附加到运行循环,此方法立即退出

If no input sources or timers are attached to the run loop, this method exits immediately

我猜你的运行循环是空的,因此BEFORE和AFTER日志将立即显示。

I guess that your run loop is empty, and therefore the "BEFORE" and "AFTER" logs will appear instantaneously.

解决问题的简单方法是

@implementation myObject

-(void)function:(id)param
{
  NSLog(@"BEFORE");
  [[NSRunLoop currentRunLoop] addTimer:[NSTimer timerWithTimeInterval:20 selector:... repeats:NO] forMode:NSDefaultRunLoopMode];
  [[NSRunLoop currentRunLoop] run];
  NSLog(@"AFTER");
}

@end

实际上,你可能会将记录AFTER的代码放入计时器调用的新方法中。通常,您不需要线程来制作动画(除非您正在做一些计算上昂贵的事情)。如果你正在做计算上昂贵的东西,你还应该考虑使用Grand Central Dispatch(GCD),它简化了后台线程的卸载计算,并将为你处理管道。

In reality, you would probably put the code that logs "AFTER" in a new method that is called by your timer. In general, you do not need threads to do animations (unless you are doing something computationally expensive). If you are doing computationally expensive stuff, you should also look into using Grand Central Dispatch (GCD), which simplifies off-loading calculations on background threads and will handle the plumbing for you.

这篇关于如何让NSRunLoop在一个单独的线程中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆