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

Objective C

Objective C Problem Overview


I wat to do something like this:

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

However, if mapView is not a class variable, this crashes. How do I check if mapView exists?

Objective C Solutions


Solution 1 - Objective C

For ordinary selectors, you can use respondsToSelector:. I'm not certain if this will work for new-style property access (as it appears you are using in this example). To test if a class responds to a given selector, use instancesRespondToSelector:.

Solution 2 - Objective C

Also, As Jason poninted out here, you can also use NSSelectorFromString to dynamically check at runtime. E.g.

if ([self respondsToSelector:NSSelectorFromString(elementName)]) 
{
    [self setValue:elementInnerText forKey:elementName];
}

Solution 3 - Objective C

Oops, found it:

if ([vc respondsToSelector:@selector(mapView)]) {

  [[vc mapView] viewWillAppear:YES];

}

Solution 4 - Objective C

Here is more than you asked for but a category I have found useful to generically handle NSObject properties:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrew JohnsonView Question on Stackoverflow
Solution 1 - Objective CdcrostaView Answer on Stackoverflow
Solution 2 - Objective CRobertView Answer on Stackoverflow
Solution 3 - Objective CAndrew JohnsonView Answer on Stackoverflow
Solution 4 - Objective CSpareTimeView Answer on Stackoverflow