I've got a simple question.
In Objective-C, when you have a method you want to call, with a return type of void, how you you call it from another method?
The way I've been doing it in my application is this:
[self nameOfMethod];
But that causes Xcode to spit out the following error:
Method '-nameOfMethod' not found (return type defaults to 'id')
Though it seems to still be executing.
Am I calling it right, or is there a better way?
Thanks!
I’m guessing you haven’t declared -nameOfMethod in the class interface and you’re calling it from another method whose implementation precedes the implementation of -nameOfMethod, i.e.:
- (void)someMethod {
[self nameOfMethod];
}
- (void)nameOfMethod {
// …
}
When the compiler is parsing -someMethod and -nameOfMethod hasn’t been declared in the class interface, it generates a warning because it doesn’t know about -nameOfMethod yet.
There are essentially two solutions for this. You could reorder the implementation file so that -nameOfMethod appears before -someMethod, but that’s not always possible. A better solution is to declare -nameOfMethod in the class interface. If -nameOfMethod is supposed to be called by clients of your class, place it in the corresponding header file. On the other hand, if -nameOfMethod is only supposed to be called inside your implementation file, use a class extension. Supposing your class is named SomeClass, this is what your header and implementation files would look like:
// SomeClass.h
@interface SomeClass : NSObject {
// … instance variables
}
// … external methods
- (void)someMethod;
@end
// SomeClass.m
#import "SomeClass.h"
@interface SomeClass () // this is a class extension
// … internal methods
- (void)nameOfMethod;
@end
@implementation SomeClass
- (void)someMethod {
[self nameOfMethod];
}
- (void)nameOfMethod {
// …
}
@end
Using class extensions, the order of method implementations won’t matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With