Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Calling a selector that the compiler does not believe exists (even though we know it does)

I have this code in a prepareForSegue method

    // Get destination view
    UIViewController *viewController = [segue destinationViewController];

    //See if it responds to a selector
    if ([viewController respondsToSelector:@selector(setSomethingOrOther:)]) {
        //if so call it with some data
        [viewController setSomethingOrOther:something];
    }

The code above means I do not have to include a reference to the actual class of the view controller being segue'd to. I can more loosely couple the two view controllers and just check if it responds to some property being set on it.

The problem is that when I do this I get the following compile time error:

No visible @interface for 'UIViewController' declares the selector 'setSomethingOrOther:'

which is true of course. I know I could get around it by including a reference to the view but I would prefer to keep it separated. How can I work around this

like image 615
Aran Mulholland Avatar asked Mar 31 '12 09:03

Aran Mulholland


2 Answers

Use the performSelector:aSelector method, then you can call an undeclared selector.

like image 78
Matthias Avatar answered Sep 29 '22 17:09

Matthias


[viewController performSelector:@selector(setSomethingOrOther:) 
                     withObject:something];
like image 38
Felix Avatar answered Sep 29 '22 17:09

Felix