objective-c - FoundationTool 中的 Runloop

标签 objective-c macos cocoa appkit 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;
}

最佳答案

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

关于objective-c - FoundationTool 中的 Runloop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7893348/

相关文章:

java - MAC OS X 自定义应用程序在 Dock 中不断弹出

python - Tkinter 按钮背景颜色在 mac os 中不起作用

ios - NSRegularExpression 验证电子邮件

swift - 我可以用代码创建一个 NSColor ,以便它可以根据深色模式或浅色模式进行更改吗?

ios - Objective-C:授予子类私有(private)变量访问权限

objective-c - 使用 Xcode 6 的 AFURLRequestSerialization 中的自动合成错误

Python 'Logger' 模块双重记录

objective-c - Cocoa 应用程序在任何 GL 函数上提供 EXC_BAD_ACCESS

ios - NSFileSystemFreeSize 返回不准确的可用磁盘空间?

ios - append 两个数组给出 [__NSCFArray insertObject :atIndex:]: mutating method sent to immutable object'