Objective-C: Should I declare private methods?

2019-01-26 09:47发布

问题:

I've been declaring private methods in class extensions, according to Best way to define private methods for a class in Objective-C.

But, I just realized that, in Xcode 4, if I leave out the declaration of a private method altogether and just implement it, the app compiles and runs without warning or error.

So, should I even bother declaring private methods in class extensions?

Why should we have to declare methods anyway? In Java, you don't... neither in Ruby.

回答1:

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
{
}


回答2:

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 ?



回答3:

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.