iPhone Development 101

iPhone 101

Code Tips

Resources

Links

Follow

TwitterRSSE-mail

More

iPhone Development 101: Objective-C:
Objective-C: Singletons

A singleton is a special kind of class where only one instance of the class exists for the current process. (In the case of an iPhone app, the one instance is shared across the entire app.) Some examples in UIKit are [UIApplication sharedApplication] (which returns the sole instance of the application itself), and [NSFileManager defaultManager] (which returns the file manager instance). Singletons can be an easy way to share data and common methods across your entire app.

Rather than create instances of the singleton class using alloc/init, you'll call a class method that will return the singleton object. You can name the class method anything, but common practice is to call it sharedName or defaultName.

@interface AwardCenter : NSObject {
    // whatever instance vars you want
}

+ (AwardCenter *)sharedCenter;   // class method to return the singleton object

- (void)customMethod; // add optional methods to customize the singleton class

@end

In the implementation (.m) file, you should create a static variable to point to the current instance. There are also a few inherited methods you should customize:

#import "AwardCenter.h"

@implementation AwardCenter

static AwardCenter *sharedAwardCenter = nil;    // static instance variable

+ (AwardCenter *)sharedCenter {    
    if (sharedAwardCenter == nil) {
        sharedAwardCenter = [[super allocWithZone:NULL] init];
    }
    return sharedAwardCenter;    
}

- (id)init {
    if ( (self = [super init]) ) {
        // your custom initialization
    }
    return self;
}

- (void)customMethod {
    // implement your custom code here
}   

// singleton methods
+ (id)allocWithZone:(NSZone *)zone {
    return [[self sharedCenter] retain];
}

- (id)copyWithZone:(NSZone *)zone {    
    return self;    
}

- (id)retain {    
    return self;
}

- (NSUInteger)retainCount {
    return NSUIntegerMax;  // denotes an object that cannot be released
}

- (void)release {
    // do nothing - we aren't releasing the singleton object.
}

- (id)autorelease {
    return self;
}

-(void)dealloc {
    [super dealloc];
}

@end

To use the singleton in your code, you'll need to #import the singleton's class header file. Then just call the sharedName class method just as you would any other object:


[[AwardCenter sharedCenter] customMethod];
 

Additional References


TopHome