问题
If I generate methods dynamically on runtime and then call them - how can I convince compiler that the class will respond to undeclared (generated) methods and make it not throw warnings?
Update in regard to answers
When I generate the methods - their name is not known at compile time. To give an example - if I have a view controller MyFooController
and it's initiated with method initWithFoo:(Foo*)foo
, I'd be able to generate method like pushMyFooControllerWithFoo:(Foo *)foo
for UINavigationController
. Hence you notice that declaring such methods would be counter-productive.
回答1:
This doesn't directly answer your question, but if I was generating method names (presumably from strings), I would call them using the string names, hence bypassing the compiler warnings.
[fooController performSelector:NSSelectorFromString(@"pushMyFooControllerWithFoo:") withObject:foo];
That way you are responsible for the validity of the generated method names.
回答2:
Since you are adding methods on runtime, so you should also invoke them with runtime function, objc_msgSend
or performSelector:withObject:
for example, so the compiler will not going to warn you anything.
回答3:
Well, if you call them, you know their signature, and if you know their signature, you can declare them, can't you?
回答4:
Declare this method in a category for NSObject and make an empty implementation:
@interface NSObject (DynamicMethodsCategory)
- (void)doSomething;
@end
@implementation NSObject (DynamicMethodsCategory)
- (void)doSomething
{
}
@end
In your object you can call it without any warnings:
@implementation MyObject
- (void)someMethod
{
[self doSomething];
}
@end
Then generate implementation of [MyObject doSomething]
dynamically, it will be called instead of NSObject's
one.
Update: Alternatively, the method can be declared in a category for the object. This suppresses the compiler's Incomplete implementation warning. However, I think this is not a good workaround, because the application will crash if the method is not created dynamically in runtime before it is called.
来源:https://stackoverflow.com/questions/7702318/objective-c-dynamically-created-methods-and-compiler-warnings