I know it is a common problem, I googled a lot and seems get no luck to solve my problem. I have a @interface TestViewController:UIViewController and in its implementation file I have a method defined:
-(void)method1 {
do something;
[self m开发者_开发技巧ethod1];//here I need to call the method itself if a statement is true and this line is where the warning TestViewController may not respond to'method1' I got
}
-(void)method2{
[self method1] //But there is no problem with this line
}
Can anyone help me? Thanks in advance!
Your method declarations are missing in the header. Just add
-(void)method1;
-(void)method2;
to your TestViewController.h file
Update:
The reason why you don't get a warning about the second call ([self method1]
within method2) is, that the compiler already knows about method1 at that point. (because the implementation occurs before method2)
Objective-C just as C uses a single pass compiler to gather all known symbols. The result is that you can only reference methods and variables that has been declared above the current scope.
You can solve this particular problem you give an example of in three ways:
Add method1
to the public interface in the header file, just as @weichsel suggested.
If you want method1
to be private then you can add it to your class by declaring an unnamed category at the top of you implementation file. Like this:
#import "Foo.h"
@interface Foo ()
-(void)method1;
@end
@implementation Foo
// ... lots of code as usual ...
@end
The third option could be regarded as hack by some, but it really a feature of the Objective-C language. Just as all methods get an implicit variable named self
that is the instance the method was called on, so do all method alsa get the implicit variable named _cmd
, that is of type SEL
, it is the selector that was used to call this method. This can be used to quickly call the same method again:
-(void)method1 {
if (someContition) {
[self performSelector:_cmd withObject:nil];
} else {
// Do other stuff...
}
}
This is most useful if you want to make sure that a particular method is always performed on the main thread:
-(void)method {
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:_cmd withObject:nil waitUntilDone:NO];
return;
}
// Do stuff only safe on main thread
}
精彩评论