FoundationTool中的Runloop

时间:2011-10-25 17:32:25

标签: objective-c macos cocoa appkit runloop

我正在写一个基础工具。我必须将线程分成不同的正在进行的任务。

我试图做线程,但它一直在崩溃。最后我想出了我需要运行自己的runloop的原因。

有人可以用一些简单的例子来帮助吗?我试过跟随代码,但它不起作用。我每次运行它都会遇到异常崩溃?如何在Foundation工具中运行线程?

@interface MyClass : NSObject
{
}
-(void) doSomething;
@end

@implementation MyClass
-(void) RunProcess:
{
    printf("test");  
}
-(void) doSomething:
{
    [NSThread detachNewThreadSelector: @selector(RunProcess:) toTarget:self withObject: nil];  
}
@end

int main(void)
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    MyClass *myObj = [[MyClass alloc] init],
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 myObj selector:@selector(doSomething:) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];

    [pool drain];
    return 0;
}

2 个答案:

答案 0 :(得分:5)

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 myObj 
        selector:@selector(doSomething:) userInfo:nil repeats:NO];

注意你的选择器是-doSomething:,带有冒号和参数,但你实现的方法是-doSomething,没有冒号和参数。实际上,您对方法(-doSomething)的声明与实现(-doSomething:)不匹配。目前还不清楚在输入你的例子时这是否只是一个错误,或者这是否真的在你的代码中。引发的例外是什么?

如果您的代码中存在此错误,则计时器最终会尝试向您不理解的MyClass对象发送消息,这很可能会引发异常。

根据+scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:的文档中的建议,您可能应该将计时器设置的方法更改为以下内容:

@interface MyClass : NSObject {

}
-(void)doSomething:(NSTimer *)timer;
@end

@implementation MyClass

-(void)doSomething:(NSTimer *)timer {
      [NSThread detachNewThreadSelector:@selector(RunProcess:)
       toTarget:self withObject:nil];  
}

@end

答案 1 :(得分:2)

如果没有看到异常,请允许我指出您正在尝试使用scheduledTimerWithTimeInterval:...在运行循环上安排计时器,而不会出现运行循环。您应该使用timerWithTimeInterval:...

创建计时器