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 (Cocoa-dev@lists.apple.com)

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/kd7qis%40gmail.com

This email sent to kd7...@gmail.com

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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 arch...@mail-archive.com

Reply via email to