Singleton classes are an important concept to understand because they exhibit an extremely useful design pattern. This idea is used throughout the iPhone SDK, for example, UIApplication has a method called sharedApplication which when called from anywhere will return the UIApplication instance which relates to the currently running application.
You can implement a singleton class in Objective-C using the following code:
MyManager.h
#import <foundation/Foundation.h>
@interface MyManager : NSObject {
NSString *someProperty;
}
@property (nonatomic, retain) NSString *someProperty;
+ (id)sharedManager;
@end
MyManager.m
#import "MyManager.h"
static MyManager *sharedMyManager = nil;
@implementation MyManager
@synthesize someProperty;
#pragma mark Singleton Methods
+ (id)sharedManager {
@synchronized(self) {
if(sharedMyManager == nil)
sharedMyManager = [[super allocWithZone:NULL] init];
}
return sharedMyManager;
}
+ (id)allocWithZone:(NSZone *)zone {
return [[self sharedManager] retain];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release {
// never release
}
- (id)autorelease {
return self;
}
- (id)init {
if (self = [super init]) {
someProperty = [[NSString alloc] initWithString:@"Default Property Value"];
}
return self;
}
- (void)dealloc {
// Should never be called, but just here for clarity really.
[someProperty release];
[super dealloc];
}
@end
Then you can reference the singleton from anywhere by calling the following function:
MyManager *sharedManager = [MyManager sharedManager];
I’ve used this extensively throughout my code for things such as creating a singleton to handle CoreLocation or CoreData functions.
EDIT: Added property to MyManager.
EDIT: Updated as per Apple’s guidelines to pass static analysis.

Hi Matt,
This has been a great help. Thank you.
My background is CAD/CAM with a lot of work in the background languages of CAD systems. But this is my first attempt at objective-c. My big idea is a vistor app for our county. A lot of Amish here and they attract many visitors.
In my viewController.h I put:
#import #import @class AmishAttractions; @interface ElkhartCountyViewController : UIViewController { IBOutlet AmishAttractions *amishAttractions; NSString *listingName; NSString *listingWebsite; } -(IBAction)gotoamishattractions; @property (nonatomic, retain) NSString *listingName; @property (nonatomic, retain) NSString *listingWebsite; + (id)sharedManager; @end In the .m file I put: #import "ElkhartCountyViewController.h" #import "AmishAttractions.h" static ElkhartCountyViewController *sharedMyManager = nil; @implementation ElkhartCountyViewController @synthesize listingName; #pragma mark Singleton Methods + (id)sharedManager { @synchronized(self) { if(sharedMyManager == nil) [[self alloc] init]; } return sharedMyManager; } + (id)allocWithZone:(NSZone *)zone { @synchronized(self) { if(sharedMyManager == nil) { sharedMyManager = [super allocWithZone:zone]; return sharedMyManager; } } return nil; } - (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (unsigned)retainCount { return UINT_MAX; //denotes an object that cannot be released } - (void)release { // never release } - (id)autorelease { return self; } - (id)init { if (self = [super init]) { listingName = [[NSString alloc] initWithString:@"Default Property Value"]; } return 0; } -(IBAction)gotoamishattractions { [self presentModalViewController:amishAttractions animated:YES]; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { // Should never be called, but just here for clarity really. [listingName release]; [super dealloc]; } @endIn the controller file I want to pass a variable to I put:
#import "AmishAttractionsAmishAcres.h" @implementation AmishAttractionsAmishAcres AmishAttractionsAmishAcres *sharedManager = [AmishAttractionsAmishAcres sharedManager]; - (void)awakeFromNib { // [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://amishacres.com"]]]; // [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[listingWebsiteList objectAtIndex:row]]]]; // [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:listingWebsite]]]; } - (IBAction)backButtonPressed { [self.parentViewController dismissModalViewControllerAnimated:YES]; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; } - (void)viewDidUnload { [super viewDidUnload]; } - (void)dealloc { [super dealloc]; } @endThe compiler tells me the initializer element is not constant.
Can you give me a clue as to what I need to do?
Thanks a lot,
Mike
I made a reusable singleton class from which you can inherit to get singleton properties. You can see source code here: http://www.devbypractice.com/reusable-singleton-class-in-objective-c-for-iphone-and-ipad/
Hi, thanks for this. I noticed that your implementation code snippet is missing an @end at the bottom of the file, and also your init method doesn’t return self. Is the latter an accident? I want to make sure it’s not some clever trick that I don’t know about.
Thanks!
@Mike – Thanks for pointing both those bugs out, I’ve updated accordingly.
Awesome example. Many thanks for this as I was fighting with my bad implementation for hours.
Hi Matt,
Thanks for this nice code.
So if singletons are never released… isn’t that like… bad?
@Bob – Short answer, no. The idea of a singleton is to model 1 object which inherently has a lifetime the same length as your application. Just like you have 1 and only 1 instance that conforms to the UIApplicationDelegate protocol. It doesn’t matter that you never release the object, because you’re not ever going to want to do that if the lifetime is the same as your application.
Does that help?
That makes sense, thanks for the explanation.
Thanks for that post. Just one question: Running the code in Instruments still shows a ‘leak’ for that class. Is this correct, resp. is that the one instance that is never released? Or am I having a bug in the code?
@pawi – You probably have a bug in the code somewhere. The singleton shouldn’t show as being leaked. What is the actual object that is being leaked?
Hi Matt, thanks for your quick reply. Now that I double-check with instruments, the leak is gone
I guess I has to clean my targets. (btw: the leak was from my old implementation. However, it passed Apple’s approval process…) Cheerz!
Ah Nuuu! To early. Still leaking. Can I send you my code? Would really appreciate your help!
Hi again,
Instead of posting my whole code, I try to explain what causes my leak:
Whenever I get the shared instance as described in your post, I want to set a property through
myManager.someProperty = [NSString stringWithFormat:@"blabla", someStringValue];
Everytime I set a property this way, it causes an NSString-Object leak… My property is synthesized.
Any Idea?
I am new to Singletons, and I do not quite know how they work. Do you have to have a separate Singleton for every variable that you want to store or can you use the same one for multiple variables. If so, how exactly would this work?
@jadodgers – you’d use the same one for multiple variables, just have an instance variable of the singleton for each variable you want. Does that make sense?
@pawi – that code itself shouldn’t leak. Is your property retained or copied? Either way it should still be fine though. You might need to show me more context in order for me to help on this one.