How to get rid of the 'undeclared selector' warning

I want to use a selector on an NSObject instance without the need for an implemented protocol. For example, there's a category method that should set an error property if the NSObject instance it's called on supports it. This is the code, and the code works as intended:

if ([self respondsToSelector:@selector(setError:)])
{
    [self performSelector:@selector(setError:) withObject:[NSError errorWithDomain:@"SomeDomain" code:1 userInfo:nil]];
}

However, the compiler doesn't see any method around with the setError: signature, so it gives me a warning, for each line that contains the @selector(setError:) snippet:

Undeclared selector 'setError:'

I don't want to have to declare a protocol to get rid of this warning, because I don't want all classes that may use this to implement anything special. Just by convention I want them to have a setError: method or property.

Is this doable? How?

Cheers,
EP


Another option would be to disable the warning with:

#pragma GCC diagnostic ignored "-Wundeclared-selector"

You can place this line in the .m file where the warning occurs.

Update:

It works also with LLVM like this:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"

... your code here ...

#pragma clang diagnostic pop

Have a look at NSSelectorFromString.

 SEL selector = NSSelectorFromString(@"setError:");
 if ([self respondsToSelector:selector])

It will allow you to create a selector at runtime, instead of at compile time through the @selector keyword, and the compiler will have no chance to complain.


I think this is because for some odd reason the selector isn't registered with the runtime.

Try registering the selector via sel_registerName() :

SEL setErrorSelector = sel_registerName("setError:");

if([self respondsToSelector:setErrorSelector]) {
   [self performSelector:setErrorSelector withObject:[NSError errorWithDomain:@"SomeDomain" code:1 userInfo:nil]];
}
链接地址: http://www.djcxy.com/p/47380.html

上一篇: 可可:打破每一个方法调用?

下一篇: 如何摆脱'未声明的选择器'警告