2

私は財団ツールを書いています。進行中のさまざまなタスクを分離するには、スレッド化を行う必要があります。

スレッド化を試みましたが、継続的にクラッシュしていました。そして最後に、独自の実行ループを実行する必要がある理由を突き止めました。

簡単な例を手伝ってくれる人はいますか?次のコードを試しましたが、うまくいきません。実行するたびに例外でクラッシュしますか? 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;
}
4

2 に答える 2

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
于 2011-10-25T17:46:02.820 に答える
2

Without seeing the exception, allow me to point out that you are trying to schedule a timer on a run loop, using scheduledTimerWithTimeInterval:..., without there being a run loop in place. You should create the timer using timerWithTimeInterval:...

于 2011-10-25T17:47:08.810 に答える