响应选择器但抛出错误

时间:2012-06-21 11:58:16

标签: ios objective-c grand-central-dispatch nsoperationqueue

- (void)TargetHit:(int)target{

    void (^threadBlock)(void) = ^{
        NSLog(@"respond to selector %d", [self respondsToSelector:@selector(changeImageOfTarget:)]);

        [[NSOperationQueue mainQueue] performSelectorOnMainThread:@selector(changeImageOfTarget:) withObject:[NSNumber numberWithInt:target] waitUntilDone:YES];
        [NSThread sleepForTimeInterval:1.0]; 
        [[NSOperationQueue mainQueue] performSelectorOnMainThread:@selector(changeImageOfTarget:) withObject:[NSNumber numberWithInt:target] waitUntilDone:YES];
    };

    dispatch_async(dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), threadBlock);
}

我可以理解为什么我的代码返回YES以响应选择器,但是当我尝试执行它时,我收到一条错误消息并且应用程序崩溃了。

[NSOperationQueue changeImageOfTarget:]: unrecognized selector sent to instance 0x6a39810'

也是如此
 [[NSThread currentThread] performSelectorOnMainThread:@selector(changeImageOfTarget:) withObject:[NSNumber numberWithInt:target] waitUntilDone:YES];

我如何在主线程上执行方法或@selector

1 个答案:

答案 0 :(得分:4)

self可能会响应选择器。问题是[NSOperationQueue mainQueue]没有。

  

我如何在主线程上执行方法或@selector?

只需在要执行操作的对象上调用它:

[self performSelectorOnMainThread:@selector(changeImageOfTarget:) withObject:[NSNumber numberWithInt:target] waitUntilDone:YES];