开发者

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

开发者 https://www.devze.com 2023-03-24 14:24 出处:网络
Let\'s say I have an objective-c .m file with the following meth开发者_如何学Pythonods defined:

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

精彩评论

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