objective-c – 如果目标支持,只执行选择器?
发布时间:2020-12-16 10:28:24 所属栏目:百科 来源:网络整理
导读:你如何称呼可选的协议方法? @protocol Foo@optional- (void) doA;- (void) doB;@end 现在我们每次要调用doA或doB时都要检查: if ([delegate respondsToSelector:@selector(doA)]) [delegate performSelector:@selector(doA)]; 那太傻了.我在NSObject上提出
你如何称呼可选的协议方法?
@protocol Foo @optional - (void) doA; - (void) doB; @end 现在我们每次要调用doA或doB时都要检查: if ([delegate respondsToSelector:@selector(doA)]) [delegate performSelector:@selector(doA)]; 那太傻了.我在NSObject上提出了一个类别,它增加了: - (void) performSelectorIfSupported: (SEL) selector { if ([self respondsToSelector:selector]) [self performSelector:selector]; } ……哪个好多了.你有一个更聪明的解决方案,或者你是否只是在每次通话前忍受条件? 解决方法
如何拦截调用的NSObject类别?使用MAObjCRuntime,它看起来像这样:
- (void)forwardInvocation:(NSInvocation *)anInvocation { id target = [anInvocation target]; SEL selector = [anInvocation selector]; for(RTProtocol *protocol in [[target class] rt_protocols]) { // check optional instance methods NSArray *methods = [protocol methodsRequired:NO instance:YES]; for (RTMethod *method in methods) { if ([method selector] == selector) { // NSLog(@"target %@'s protocol %@ contains selector %@",target,protocol,NSStringFromSelector(selector)); // just drop the invocation return; } } } // selector does not seem to be part of any optional protocol // use default NSObject implementation: [self doesNotRecognizeSelector:selector]; } 您可以轻松添加对合并协议和诸如此类的检查,但对于所述情况,这应该已经有效. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |