How to supress a "Class may not respond to '-method' warning with variable method name?
How can I prevent this warning with a variable selector name?
NSString *method开发者_运维问答Name;
SEL method = NSSelectorFromString(methodName);
if ([self respondsToSelector:method]) {
if ([methodName hasSuffix:@":"])
[self method:dict];
else
[self method];
}
Use
[self performSelector:method];
Instead of
[self method];
And
[self performSelector:method withObject:dict];
Instead of
[self method:dict];
sidyll's answer works, but there is a better solution.
Generally, you would declare a protocol:
@protocol MyOptionalMethods
@optional
- (void)method:(NSDictionary*)dict;
@end
And declare your object conforms to the protocol:
id<MyOptionalMethods> foo;
UIView*<MyOptionalMethods> bar; // it'll be a subclass o' UIView and may implement pro to
Then check:
if ([foo respondsToSelector:@selector(method:)])
[foo method: dict];
That way, the compiler has the opportunity to fully type check all arguments. As well, this pattern is not limited to methods that take no arguments or a single object argument.
As well, this is future-proofed against migration to ARC (since ARC rightly complains mightily about the brittleness of performSelector:).
精彩评论