开发者

is there an equivalent of method declaration/definition separation for Objective-C messages?

Let's say I have an objective-c .m file with the following meth开发者_如何学Pythonods defined:

- (void) doOneThing {
      [self doAnotherThing];
}

- (void) doAnotherThing {
       [self stillOtherThings];
}

if I compile this, xcode will throw me a warning that the class may not respond to -doAnotherThings, because doAnotherThing is defined below -doOneThing and the compiler doesn't know about -doAnotherThing yet when it's compiling -doOneThing. Of course, the code compiles properly and does in fact work, but I'd like to get rid of that warning message.

The trivial way to solve this problem would be to just define -doAnotherThing before -doOneThing, but sometimes I like to group related methods in the source code in ways that make it hard to re-order. If this were C, I could do something like:

void doAnotherThing();

void doOneThing() {
    doAnotherThing();
}

void doAnotherThing() {
     ...still other things...
}

separating the definition from the declaration. Is there a way to do something like this in objective-c, or otherwise solve my problem?


The typical way to deal with this is as follows:

//in DoThings.h
@interface DoThings : NSObject {
    //instance variables go here
}

//public methods go here
- (void) doAPublicThing;

//properties go here

@end


//in DoThings.m
@interface DoThings (Private)
- (void)doOneThing;
- (void)doAnotherThing;
- (void)stillOtherThings;
@end

@implementation DoThings

- (void) doAPublicThing {
    [self doOneThing];
}

- (void) doOneThing {
    [self doAnotherThing];
}

- (void) doAnotherThing {
    [self stillOtherThings];
}

@end


You need to define these method declarations in your header file for the class:

@interface MyCustomClass : NSObject

- (void) doOneThing;
- (void) doAnotherThing;

@end

Then everything will work as intended.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜