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

test picture test · Feb 23, 2012 · Viewed 12.1k times · Source

I have a lot question marks tolling above my head. What I don't get is before xcode 4.3 I needed to declare forward declarations (for private methods) in my implementation file.

Like in my .m file:

// deleting this with xcode 4.3 the below code still does work 
// in previous versions i had to put this because otherwise the compiler can't find methodFirst
@interface DetailViewController ()
- (void)methodFirst;
- (void)methodSecond;
@end


@implementation DetailViewController

- (void) methodSecond
{
   // if i delete the forward declaration now adays i dont get a compiler error that he cant find method first
   [self methodFirst];
}

- (void) methodFirst
{
}

@end

Now it seems I don't need to do that anymore? Did Apple update the compiler so that it isn't needed anymore to put forward declarations?

I can't find any reference to an official Apple source about this change. I wonder what other people have encountered in their new environment.

Answer

BJ Homer picture BJ Homer · Feb 23, 2012

As of the LLVM Compiler version shipped with Xcode 4.3, if you try to call a method that the compiler has not previously seen, it will look in the rest of the current @implementation block to see if that method has been declared later. If so, then it uses that, and you don't get a warning. Hence, as of Xcode 4.3, there's much less need to pre-declare your internal methods. Clearly, you still need to declare methods that are publicly exposed to other classes.

This change was noted in the release notes of some of the Xcode 4.3 betas, but apparently didn't make it into the "What's New in Xcode 4.3" final documentation.

Unlike has been suggested in other answers, this is not just an "Undeclared Selector" warning that has been turned off by default. In fact, if you're using ARC, unrecognized selectors are still hard errors. Try calling [self myNonexistentMethod] and you'll see; the compiler still complains.