Objective-C: Should I declare private methods?

爱⌒轻易说出口 提交于 2019-11-29 10:04:18

A method definition only needs to be defined if the caller is declared before the method. For consistency I would recommend defining your private methods in the extension.

-(void)somemethod
{
}

-(void)callermethod
{
    //No warning because somemethod was implemented already
    [self somemethod];
}

-(void)callermethod2
{
    //Warning here if somemethod2 is not defined in the header or some extension
    [self somemethod2];
}

-(void)somemethod2
{
}
ravron

This answer has already been correctly answered by Joe for Xcode prior to v4.3. However, in v4.3 and above, not only do private methods not need to be declared, but declaration order is now irrelevant. For details, see:

Private Methods in Objective-C, in Xcode 4.3 I no longer need to declare them in my implementation file ?

This will compile and run fine without declaration:

- (void)foo {
}

- (void)bar {
    [self foo];
}

But last I checked, this will give a warning:

- (void)bar {
    [self foo];
}

- (void)foo {
}

In other words, it's just like in C: a declaration is not necessary if the definition comes before any use. C requires this to avoid having to add an extra pass to the compiler (one to find the functions and then one to actually parse them). As for whether you should declare them when not necessary, it's really up to the style of the codebase you're working with.

As for other languages that don't require declarations, some just go ahead with the extra pass, while others don't need to know the number and types of the arguments or the return type at compile time (they look up functions at runtime instead, or they don't have strongly-typed variables to begin with so it doesn't "matter") so they can just skip it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!