0
- (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在主线程上?

4

1 回答 1

4

self可能会响应选择器。问题是[NSOperationQueue mainQueue]事实并非如此。

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

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

[self performSelectorOnMainThread:@selector(changeImageOfTarget:) withObject:[NSNumber numberWithInt:target] waitUntilDone:YES];
于 2012-06-21T12:00:46.307 回答