开发者

Calling a method with return type "void" in same file

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 开发者_C百科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.


You need to make sure that your interface file contains a definition for nameOfMethod - so;

-(void) nameOfMethod;


You're calling it correctly, but make sure that the interface for your (void) method is in your .h file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜