Andrew Johnson
Andrew Johnson

Reputation: 13286

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

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?

Upvotes: 55

Views: 35004

Answers (4)

SpareTime
SpareTime

Reputation: 129

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

Upvotes: 0

Robert
Robert

Reputation: 38213

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];
}

Upvotes: 39

dcrosta
dcrosta

Reputation: 26258

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:.

Upvotes: 50

Andrew Johnson
Andrew Johnson

Reputation: 13286

Oops, found it:

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

  [[vc mapView] viewWillAppear:YES];

}

Upvotes: 32

Related Questions