我理解告诉您防止无法识别的选择器的答案,因为这是首选方法。
但是在您没有该选项的情况下(例如在我的情况下,Cocoa 内部在调用堆栈的下方混乱)您确实可以在尝试时捕获无法识别的选择器。
概念验证代码:
// Do a really bad cast from NSObject to NSButton
// to get something to demonstrate on
NSButton *object = (NSButton*)[[NSObject alloc] init];
@try{
// Log the description as the method exists
// on both NSObject and NSButton
NSLog(@"%@", [object description]);
// Send an unrecognized selector to NSObject
[object bounds];
} @catch(NSException *e){
NSLog(@"Catch");
} @finally {
NSLog(@"Finally");
}
// Print the description to prove continued execution
NSLog(@"Description again: %@", [object description]);
输出:
2019-02-26 14:11:04.246050+0100 app[46152:172456] <NSObject: 0x60000000a6f0>
2019-02-26 14:11:04.246130+0100 app[46152:172456] -[NSObject bounds]: unrecognized selector sent to instance 0x60000000a6f0
2019-02-26 14:11:04.246226+0100 app[46152:172456] Catch
2019-02-26 14:11:04.246242+0100 app[46152:172456] Finally
2019-02-26 14:11:04.246258+0100 app[46152:172456] Description again: <NSObject: 0x60000000a6f0>
如您所见,异常仍记录到控制台,但代码执行仍在继续。