views:

642

answers:

1

Can anyone explain why a singleton instance of the MyCLController class is used in the sample iphone app LocateMe found here

as well as the overriding of retain, retainCount, release, and autorelease? Any help would be very much appreciated!!

+5  A: 

Because only a single instance of MyCLController is ever needed in the application.

The singleton implementation in that example is the über-defensive pattern. It overrides all of the other methods to prevent you from ever potentially deallocating the instance.

Personally, I never go through such hoops (and the documentation will be changed in the future), preferring to do a dead simple +sharedInstance method instead:

+ sharedInstance
{
    static id sharedInstance = nil;
    if (!sharedInstance) {
        sharedInstance = [self alloc];
        sharedInstance = [sharedInstance init];
    }

    return sharedInstance;
}

(1) Yes, I broke up the alloc/init on purpose. It lets anything in the -init method call +sharedInstance without a problem.

(2) No, this doesn't deal with multithreading. For that, I use GCD's dispatch_once(). On the iPhone, you would need a slightly different pattern. @synchronized() works, but is overhead.

One of the reason's why I find the über-defensive pattern to be disconcerting is because, frankly, if you have a singleton class and you are causing it to be deallocated through over-release, your code is broken and that kind of bug should not be obscured. If anything, the code should fail catastrophically. As well, there are a number of situations where a singleton class may also be valid with individual instances, too.

bbum