Check if a method exists

前端 未结 5 2054
半阙折子戏
半阙折子戏 2020-12-13 01:58

Is there any way I can test if a method exists in Objective-C?

I\'m trying to add a guard to see if my object has the method before calling it.

5条回答
  •  情书的邮戳
    2020-12-13 02:36

    You're looking for respondsToSelector:-

    if ([foo respondsToSelector: @selector(bar)] {
      [foo bar];
    }
    

    As Donal says the above tells you that foo can definitely handle receiving the bar selector. However, if foo's a proxy that forwards bar to some underlying object that will receive the bar message, then respondsToSelector: will tell you NO, even though the message will be forwarded to an object that responds to bar.

提交回复
热议问题