- (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
? 最佳答案
self
可能会响应选择器。问题是[NSOperationQueue mainQueue]
没有。
如何在主线程上执行方法或@selector?
只需在要执行操作的对象上调用它即可:
[self performSelectorOnMainThread:@selector(changeImageOfTarget:) withObject:[NSNumber numberWithInt:target] waitUntilDone:YES];
关于ios - 响应选择器但抛出错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11137641/