Sending a message to an object using a selector and NSSelectorFromString

The following will pass the respondsToSelector test, but SIGABRT on the actual call to [viewController selector] or [viewController action:selector] . Stack trace status: NSInvalidArgumentException, reason: - [MyViewController selector]: unrecognized selector.

[viewController @selector(selector)] will result in a compilation error (error: expected ":" before the "selector").

When the selector is hardcoded, everything works well.

How to send a message to an object through a 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]; } } } 
+6
source share
3 answers
 [self performSelector:@selector(notifyViewControllers:) withObject: message]; 
+10
source

Try

 [viewController performSelector:selector]; 

Also check out the other NSObject methods in the performSelector 'family' file - with them you can easily call the selector with a delay and / or background thread.

+4
source

It may be useful to know how to do this if you cannot use performSelector, perhaps because the selector string should be used in the protocol method:

To enable parameters that support the selector, it should be specified as follows:

 NSString *stringForSelector = @"doSomethingAwesome:"; // notice the colon 

Suppose we handle tap

 UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:NSSelectorFromString(stringForSelector)]; 

The UIGestureRecognizer class allows the recognizer to be used in the action callback:

 - (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer; 

So, to do something amazing on Tap, we could write:

 - (void)doSomethingAwesome:(UITapGestureRecognizer *)tapGesture { // gesture handling with UIGestureRecognizer availability } 
+2
source

Source: https://habr.com/ru/post/891705/


All Articles