On Jun 12, 2008, at 10:21 PM, Kyle Sluder wrote:

If you're implementing
the singleton pattern, for example, you would override -init
differently.

In most cases, I would strongly suggest *not* doing anything differently if you are making a singleton. If you want something to be a singleton, don't follow the "ensure there is only one instance of this class" example. Instead, just implement a +sharedWhatever method that returns a global, and does an +alloc/-init if necessary:

  @implementation Foo

  + (id)sharedFoo {
      static id sharedFoo = nil;

      if (sharedFoo == nil) {
          sharedFoo = [[self alloc] init];
      }

      return sharedFoo;
  }

  @end

No overrides of +allocWithZone:, -retain, -release, -autorelease or anything of the sort. (Obviously if you're writing code that will invoke +sharedFoo from multiple threads, you'll want to do appropriate synchronization as well.)

This will be much easier to write reasonable unit tests for, since you can still separately instantiate it (and therefore won't have to "reset" anything after each). You will also be prepared for cases where you need to promote something that starts as a singleton to a non-singleton.

  -- Chris

_______________________________________________

Cocoa-dev mailing list ([email protected])

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to