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

夙愿已清 提交于 2019-12-07 05:32:09

问题


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


回答1:


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




回答2:


[viewController performSelector:@selector(setSomethingOrOther:) 
                     withObject:something];



回答3:


You can also do this

[(id)viewController setSomethingOrOther:something];

in some situation, but I the compiler will complain if it does not know about the existence of setSomethingOrOther: at all, like a library that you haven't included the header for.



来源:https://stackoverflow.com/questions/9954886/objective-c-calling-a-selector-that-the-compiler-does-not-believe-exists-even-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!