objective-c 在 Objective C 中,你能检查一个对象是否有特定的属性或消息吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1535190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:19:57  来源:igfitidea点击:

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

objective-c

提问by Andrew Johnson

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?

但是,如果 mapView 不是类变量,则会崩溃。如何检查 mapView 是否存在?

采纳答案by dcrosta

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

对于普通选择器,您可以使用respondsToSelector:. 我不确定这是否适用于新式属性访问(正如您在本示例中使用的那样)。要测试类是否响应给定选择器,请使用instancesRespondToSelector:.

回答by Robert

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

此外,正如 Jason 在此处指出的那样,您还可以使用NSSelectorFromString来在运行时动态检查。例如

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

回答by Andrew Johnson

Oops, found it:

哎呀,找到了:

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

  [[vc mapView] viewWillAppear:YES];

}

回答by SpareTime

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

这比你要求的要多,但我发现一个类别对于一般处理 NSObject 属性很有用:

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

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