• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: singleton pattern in cocoa
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: singleton pattern in cocoa


  • Subject: Re: singleton pattern in cocoa
  • From: Christopher J Kemsley <email@hidden>
  • Date: Mon, 14 Sep 2009 09:43:53 -0700

About the only thing that I'd recommend is that the "static" be inside the +sharedSingleton method so that you aren't able to take the cheap- way-out and call that variable directly in other class methods before it's created.

For the rest of it: it seems to follow Apple's patterns - for instance, [NSNotificationCenter defaultCenter] and [NSStatusBar systemStatusBar] and [UIAccelerometer sharedAccelerometer] and sharedAddressBook... etc

A lot of things use the sharedMyClass, but a lot (though fewer) of things also use their own name.

That method of singletons is pretty common though.

On 10 Sep 2009, at 1:07 PM, Manuel Grau wrote:

Hi all,

As I come from java world, I was trying to implement the singleton pattern, very usual in java. After searching in internet I found this code from wikipedia:

@interface MySingleton : NSObject
{
}

+ (MySingleton *)sharedSingleton;
@end

@implementation MySingleton

static MySingleton *sharedSingleton;

+ (MySingleton *)sharedSingleton
{
 @synchronized(self)
 {
   if (!sharedSingleton)
     [[MySingleton alloc] init];

   return sharedSingleton;
 }
}

+(id)alloc
{
@synchronized(self)
{
NSAssert(sharedSingleton == nil, @"Attempted to allocate a second instance of a singleton.");
sharedSingleton = [super alloc];
return sharedSingleton;
}
}


@end

What do you think about this implementation? I'm newbie with cocoa and I'm not sure.

Thanks.


_______________________________________________

Cocoa-dev mailing list (email@hidden)

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:
This email sent to email@hidden

_______________________________________________

Cocoa-dev mailing list (email@hidden)

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:
This email sent to email@hidden


References: 
 >singleton pattern in cocoa (From: Manuel Grau <email@hidden>)

  • Prev by Date: Re: coding NSNumber in NSArray?
  • Next by Date: Re: singleton pattern in cocoa
  • Previous by thread: Re: singleton pattern in cocoa
  • Next by thread: Re: singleton pattern in cocoa
  • Index(es):
    • Date
    • Thread