RLT*_*RLT 2 macos cocoa objective-c 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;
}
Run Code Online (Sandbox Code Playgroud)
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 myObj
selector:@selector(doSomething:) userInfo:nil repeats:NO];
Run Code Online (Sandbox Code Playgroud)
请注意,您的选择器-doSomething:带有冒号和参数,但实现的方法是-doSomething没有冒号和参数.实际上,你对method(-doSomething)的声明与implementation(-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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
270 次 |
| 最近记录: |