【问题标题】:is there an equivalent of method declaration/definition separation for Objective-C messages?Objective-C消息是否有等效的方法声明/定义分离?
【发布时间】:2011-08-03 08:21:48
【问题描述】:

假设我有一个objective-c .m 文件,其中定义了以下方法:

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

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

如果我编译它,xcode 将向我发出警告,指出该类可能不会响应 -doOneThings,因为 doAnotherThing 在 -doOneThing 下面定义,并且编译器在编译 -doOneThing 时还不知道 -doAnotherThing。当然,代码可以正确编译并且确实可以正常工作,但我想摆脱该警告消息。

解决这个问题的简单方法是在 -doOneThing 之前定义 -doAnotherThing,但有时我喜欢将源代码中的相关方法以难以重新排序的方式分组。如果这是 C,我可以这样做:

void doAnotherThing();

void doOneThing() {
    doAnotherThing();
}

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

将定义与声明分开。有没有办法在objective-c中做这样的事情,或者以其他方式解决我的问题?

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    典型的处理方式如下:

    //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
    

    【讨论】:

    • 您可以将“private”这个词去掉,并按照here的描述将其作为扩展名
    • 谢谢,这正是我需要做的:)
    【解决方案2】:

    您需要在类的头文件中定义这些方法声明:

    @interface MyCustomClass : NSObject
    
    - (void) doOneThing;
    - (void) doAnotherThing;
    
    @end
    

    然后一切都会按预期进行。

    【讨论】:

    • 这可行,但也会使 doOneThingdoAnotherThing 成为班级的公共成员。如果不希望这样做,那么您应该在私有类别中声明这些方法,作为类的 .m 文件的一部分(请参阅下面的答案以获取示例)。
    猜你喜欢
    • 2010-12-11
    • 2016-06-17
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2012-06-16
    相关资源
    最近更新 更多