How to test a protocol for a method?

心已入冬 提交于 2019-12-02 23:19:48

That's a tricky one. So if I'm understanding your question correctly, you want to find out, at runtime, whether the map view sends the mapView:didSelectAnnotationView: message to its delegate. But you can't use conformsToProtocol: or respondsToSelector: because you're implementing the delegate so obviously you're adopting the protocol and implementing the method.

The only thing I can think of is to check for some other method that was added to MKMapView (not the delegate) in iOS 4, like: mapRectThatFits:.

Another possibility is to use the Objective-C runtime library to query the Protocol object. But this is probably overkill, and also I don't think it will work because the Protocol object is created by the compiler when you build your app, and it's possible you'll get the UIKit SDK-defined MKMapViewDelegate protocol object instead of whatever the runtime was compiled with.

Kendall Helmstetter Gelner

Because there is no object instance you can ask if it responds to a message selector, and you already know the protocol is supported but you are just looking for one method within - you need to use protocol_getMethodDescription, like so (method is class instance and optional) where you check for a nil return value:

#import <objc/runtime.h>

struct objc_method_description hasMethod = protocol_getMethodDescription(@protocol(MKMapViewDelegate), @selector(mapView:didSelectAnnotationView:), NO, YES);

if ( hasMethod.name != NULL )
{
...
}

I think you want NSObject conformsToProtocol - something like:

BOOL test = [myObject conformsToProtocol:@protocol(MKMapViewDelegate)];
Chris Thompson

I would use the respondsToSelector: method because that allows you to check for specific methods (which it sounds like you're doing, otherwise, if you're looking to check for a specific protocol, @Eric's answer is a good one). This SO post talks about using it this way.

Basically, the way you'd use it is

SEL methodName = @selector(mymethod:);
BOOL test = [object respondsToSelector:methodName];

I've taken a slightly different approach.

I simply use an #ifdef (__iPHONE_OS_VERSION_MIN_REQUIRED... and add observer if necessary, along with using the -mapview:didSelectAnnotationView: delegate method.

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