以下将传递respondsToSelector测试,但SIGABRT实际调用[viewController选择器]或[viewController action:selector].堆栈跟踪状态’NSInvalidArgumentException,原因: – [MyViewController选择器]:无法识别的选择器’.
[viewController @selector(selector)]将导致编译错误(错误:在’selector’之前预期’:’).
当选择器是硬编码时,一切都很好.
如何通过选择器向对象发送消息?
-(void) notifyViewControllers:(NSString*) message { if(!message) return; SEL selector = NSSelectorFromString(message); if(!selector) return; NSArray* viewControllers = [self.tabBarController viewControllers]; if(!viewControllers) return; for (UIViewController* viewController in viewControllers) { if(!viewController) continue; if ([viewController respondsToSelector:selector]) { // [viewController selector]; [viewController action:selector]; } } }
解决方法
[self performSelector:@selector(notifyViewControllers:) withObject: message];