2006-02-17 14:11:29 Singleton instance in Obj-C/Xcode
Here's one standard way to do a singleton instance in Objective-C:
( objc )
  1  +(id)singletonInstance {
2 static id singletonObject = nil;
3 if (singletonObject == nil) {
4 singletonObject = [self new];
5 [singletonObject setup];
6 }
7 return singletonObject;
8 }


which is fine for many purposes, but then schwatoo clued me in to the fact that this scheme doesn't work for objects instantiated in nib files, for which the following works:

( objc )
  1  static SomeObject *singleton = NULL;
2
3 @implementation SomeObject
4
5 +(id)singletonInstance {
6 return( singleton );
7 }
8
9 -(id)init {
10 if ((self = [super init]) != NULL)
11 if (singleton == NULL)
12 singleton = self;
13 return( self );
14 }
15
16 @end


I'll also add that the Apple Cocoa docs here give a fuller set of rules for making a zone-ready singleton object thusly:

( objc )
  1  static MyGizmoClass *sharedGizmoManager = nil;
2
3 +(MyGizmoClass*)sharedManager {
4 @synchronized(self) {
5 if (sharedGizmoManager == nil)
6 [[self alloc] init];
7 }
8 return sharedGizmoManager;
9 }
10
11 +(id)allocWithZone:(NSZone *)zone {
12 @synchronized(self) {
13 if (sharedGizmoManager == nil) {
14 sharedGizmoManager = [super allocWithZone:zone];
15 return sharedGizmoManager;
16 }
17 }
18 return nil;
19 }
20
21 -(id)copyWithZone:(NSZone *)zone {
22 return self;
23 }
24
25 -(id)retain {
26 return self;
27 }
28
29 -(unsigned)retainCount {
30 return UINT_MAX; //denotes an object that cannot be released
31 }
32
33 -(void)release {
34 //do nothing
35 }
36
37 -(id)autorelease {
38 return self;
39 }
  • Stelian Iancu (Thu, February 23rd, 2012, 7:04am UTC)
    You should update this entry with the dispatch_once way of creating a singleton.

Leave a comment