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

前端 未结 4 1389
既然无缘
既然无缘 2020-12-24 10:47

I wat to do something like this:

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

However, if mapView is not a class variab

相关标签:
4条回答
  • 2020-12-24 11:12

    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 讨论(0)
  • 2020-12-24 11:26

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

    0 讨论(0)
  • 2020-12-24 11:26

    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];
    }
    
    0 讨论(0)
  • 2020-12-24 11:30

    Oops, found it:

    if ([vc respondsToSelector:@selector(mapView)]) {
    
      [[vc mapView] viewWillAppear:YES];
    
    }
    
    0 讨论(0)
提交回复
热议问题