I am iterating through an NSArray that contains many different types of objects. There are many methods to figure out what class the object is. However, I haven't been able to find a good way to find out if an object can implement a particular function. I can put it in a try-catch but it will still output an error message in the console even if I'm catching the error. Is there a better way to do this?
我正在迭代包含许多不同类型对象的NSArray。有很多方法可以确定对象是什么类。但是,我无法找到一个好方法来确定对象是否可以实现特定的功能。我可以把它放在try-catch中,但即使我正在捕获错误,它仍会在控制台中输出错误消息。有一个更好的方法吗?
Simple example:
@try {
if ([element lowercaseString]) {
//do something
}
}
@catch (id theException) {
// do something else
}
3 个解决方案
#1
As suggested, you can use respondsToSelector:
message declared on NSObject
. The provided code would be like
如建议的那样,您可以使用在NSObject上声明的respondsToSelector:消息。提供的代码就像
if ([element respondsToSelector:@selector(lowercaseString)]) {
// ... do work
}
#2
Look at NSObject's respondsToSelector method
查看NSObject的respondsToSelector方法
#3
A nice generic category to have in your code is this:
您的代码中有一个很好的通用类别:
@interface NSObject (KMExtensions)
- (id)performSelectorIfResponds:(SEL)aSelector;
- (id)performSelectorIfResponds:(SEL)aSelector withObject:(id)anObject;
@end
@implementation NSObject (KMExtensions)
- (id)performSelectorIfResponds:(SEL)aSelector
{
if ( [self respondsToSelector:aSelector] ) {
return [self performSelector:aSelector];
}
return NULL;
}
- (id)performSelectorIfResponds:(SEL)aSelector withObject:(id)anObject
{
if ( [self respondsToSelector:aSelector] ) {
return [self performSelector:aSelector withObject:anObject];
}
return NULL;
}
@end
And then you can use:
然后你可以使用:
[element performSelectorIfResponds:@selector(lowercaseString)];
#1
As suggested, you can use respondsToSelector:
message declared on NSObject
. The provided code would be like
如建议的那样,您可以使用在NSObject上声明的respondsToSelector:消息。提供的代码就像
if ([element respondsToSelector:@selector(lowercaseString)]) {
// ... do work
}
#2
Look at NSObject's respondsToSelector method
查看NSObject的respondsToSelector方法
#3
A nice generic category to have in your code is this:
您的代码中有一个很好的通用类别:
@interface NSObject (KMExtensions)
- (id)performSelectorIfResponds:(SEL)aSelector;
- (id)performSelectorIfResponds:(SEL)aSelector withObject:(id)anObject;
@end
@implementation NSObject (KMExtensions)
- (id)performSelectorIfResponds:(SEL)aSelector
{
if ( [self respondsToSelector:aSelector] ) {
return [self performSelector:aSelector];
}
return NULL;
}
- (id)performSelectorIfResponds:(SEL)aSelector withObject:(id)anObject
{
if ( [self respondsToSelector:aSelector] ) {
return [self performSelector:aSelector withObject:anObject];
}
return NULL;
}
@end
And then you can use:
然后你可以使用:
[element performSelectorIfResponds:@selector(lowercaseString)];