In Objective-C, can you check if an object has a specific property or message?

I wanted to do something like this:

if (viewController.mapView) [viewController.mapView someMethod]; 

However, if mapView is not a class variable, this is a failure. How to check if mapView exists?

+43
objective-c
Oct 08 '09 at 1:44
source share
4 answers

For regular selectors, you can use respondsToSelector: I'm not sure if this will work to access the properties of the new style (as you seem to use in this example). To check if a class matches this selector, use instancesRespondToSelector:

+43
08 Oct '09 at 1:49
source share

Besides As Jason poninted out here , you can also use NSSelectorFromString for dynamic checking at runtime. For example.

 if ([self respondsToSelector:NSSelectorFromString(elementName)]) { [self setValue:elementInnerText forKey:elementName]; } 
+31
Apr 18 '12 at 9:50
source share

Oh, found this:

 if ([vc respondsToSelector:@selector(mapView)]) { [[vc mapView] viewWillAppear:YES]; } 
+29
Oct 08 '09 at 1:48
source share

Here is more than you requested, but a category that I found useful for the general NSObject property:

http://www.whynotsometime.com/Why_Not_Sometime/Category_Enhancing_NSObject.html

0
Jan 04 '14 at 20:13
source share



All Articles