开发者

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 ex开发者_Python百科ists?


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


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


Oops, found it:

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

  [[vc mapView] viewWillAppear:YES];

}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜