【问题标题】:Runloop in FoundationToolFoundationTool 中的 Runloop
【发布时间】:2011-10-25 17:32:24
【问题描述】:

我正在编写一个基础工具。我必须做线程来分离不同的正在进行的任务。

我试图做线程,但它不断地崩溃。最后我找到了原因,我需要运行自己的 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;
}

【问题讨论】:

  • -RunProcess: 的实现在哪里?
  • 这只是我为解释问题而写的示例。无论如何我更新了上面的代码。

标签: objective-c macos cocoa appkit runloop


【解决方案1】:
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

【讨论】:

  • 确实,sn-p中的方法定义有冒号,表示这段代码编译失败。
  • 非常感谢。这让我发疯了。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多