One of my most used design patterns when developing for iOS is the singleton pattern. It’s an extremely powerful way to share data between different parts of code without having to pass the data around manually. More about the singleton pattern and other patterns can be found in this excellent book:
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 = [[self alloc] init];
}
return sharedMyManager;
}
- (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.
}
@end
If you are not using Automatic Reference Counting (ARC), then you should use the following code:
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
}
- (oneway 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.
EDIT: Updated to support ARC.


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.
I still dont quite understand how to implement it. After you get the “MyManager *sharedManager = [MyManager sharedManager];” how do you use that to extract and change each variable in the Singleton?
@Jsdodgers – you would then use that MyManager variable just as you would any other such as:
MyManager *manager = [MyManager sharedInstance];
manager.someStringVariable = @”new string”;
Where someStringVariable is an instance variable of type NSString* and set as a property.
so all i have to do is add them to the @interface and then make them a property and synthesize them, and i do not have to change any other code?
Im confused with the -(id) init, is that just for an example and you will not need that or will you have to init each variable that you want to add? I think that the property being initialized in the singleton is mostly what i was confused with.
Thanks for the helpful and fast replies though =)
@Jsdodgers – That’s correct about adding to the interface and then synthesize them. The -init method is there for you to initialise any variables just like you would with any object. So you might want to set your string ivar to a default value for instance.
I hope that helps you!
Wow that was a fast reply. Do you have to init variables or can u just initialize them somewhere else in your code?
@Jsdodgers – you can initialise them wherever you want, it just makes sense to set default values in -init.
Ok thanks I think I understand how they work now =)
Hi Matt,
I’m new to iPhone dev and was having a looking at how Singletons are implemented in Obj-C.
Normally in C++ implementations you’d make the constructors private so that callers would *only* be able to access the instance through the ‘sharedManager’ method.
Here it seems that you can still do:
MyManager* m = [[MyManager alloc]init];
My previous understanding was that the singleton pattern was about restricting restricting the instantiation of a class to one object.
Any help or advice in trying to resolve this ?
thanks
jb
@jb – the same thing can be done with objective-c singletons that you mention. Look at the alloc function in my implementation:
+ (id)allocWithZone:(NSZone *)zone { return [[self sharedManager] retain]; }That is returning the sharedManager object itself, so any call to [MyManager alloc] will return the same instance.
You can of course change it so you *can* have multiple instances if you want – just need to do the right thing in alloc.
@Matt,
Apologies, I didn’t realise that alloc invokes allocWithZone.
thanks for getting back to me so quickly!
cheers
jb
I was wondering something else. The singleton is working perfectly (thanks!), but I was wondering why in the init, you do if(self=[super init]) if nothing is being tested in the if statement, and it is just setting self to [super init], which can be done without an if statement.
@Jsdodgers – assignment usually returns the value itself, so x = 3 returns 3. So, self=[super init] is the same as:
I just like to do it in one line as it seems neater.
The point of testing is that the base class might not have been able to init the object (although this really should never happen).
Very helpful – thanks very much!
Hi Matt,
At some user action, I would like to release the mymanager object and start with a fresh copy of it. Of course I want to do it taking properly care of the memory. Any suggestion?
This is what I have in the init method of myManager singleton class
- (id)init {
if(self = [super init]) {
photoDictionary = [[NSMutableDictionary alloc] initWithCapacity:3];
type = [[NSString alloc] init];
description = [[NSString alloc] init];
firstName = [[NSString alloc] init];
lastName = [[NSString alloc] init];
}
return self;
}
When the user dismisses the alert, I want to start from the beginning, so mymanager object should not have any value. This is what I did:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
[self.navigationController popToRootViewControllerAnimated:NO];
[sharedManager init];
}
Thank you,
@seycho1981 – My advice would be to give it a function that clears the various bits of the class properly. So like so:
- (void)clear { [photoDictionary release]; photoDictionary = [[NSMutableDictionary alloc] initWithCapacity:3]; [type release]; type = [[NSString alloc] init]; [description release]; description = [[NSString alloc] init]; [firstName release]; firstName = [[NSString alloc] init]; [lastName release]; lastName = [[NSString alloc] init]; }Thank you!
I think “forced” Singletons are a bad idea. I’ve never found myself trying to allocate a “second” Singleton in normal code, so the code to prevent additional allocations is unnecessary. The code can prevent future scaling, where you want to run multiple instances of the singleton on separate threads. The “forced” singleton doesn’t allow you to create more than one instance.
The big issue with a forced single instance, is that you can’t run unit tests without test state being dependent on the “cleanup” of the previous tests. Tests are much more reliable when they don’t depend on each other. A clean method can help, but it’s not the best solution. For example, what if you forget to clean up a new variable that you just added to the class.
I’m working on a new blog post to talk about the Singleton and unit testing. For now my first unit testing post is up: http://paulsolt.com/2010/11/iphone-unit-testing-explained-part-1/
In my “singleton” ImageCache, I only use the following code to implement the singleton shared instance method. The sharedCache works the same, but I can now create and cleanup instances of the the ImageCache. I cleanup all memory in the dealloc to prevent leaks. The other method, setSharedImageCache: allows me to switch my current “singleton” with another object. It’s very necessary for testing. Note: this singleton’s implementation won’t scale across multiple threads, since it synchronizes on the class.
// ImageCache.m static ImageCache *sharedImageCache; @implementation ImageCache // ... other logic for ImageCache // Synchronized for thread safety, only one thread at a time + (void)setSharedImageCache:(ImageCache *)cache { @synchronized(self) { if(sharedImageCache != cache) { [cache retain]; [sharedImageCache release]; sharedImageCache = cache; } } } // Synchronized for thread safety, only one thread at a time + (ImageCache *)sharedImageCache { @synchronized(self) { //ALog(@"ImageCache.sharedImageCache"); if(!sharedImageCache) { sharedImageCache = [[ImageCache alloc] init]; } } return sharedImageCache; } @end@Paul – That’s a complete design decision that is up to the user. It might be absolutely desirable to ensure that the Singleton can never ever be dealloc’ed and replaced. I wouldn’t say that this is at all a bad thing.
Your comment about unit tests I would say should be solved by completely restarting your process for each test if that’s what you need to do. How do you know that any of the Singletons inside Cocoa haven’t been mutated? If you’re needing to be worried about ensuring the state is exactly the same at the start of each unit test then you should be running them separately – that’s the only way you can ensure that.
This is Apple’s documentation on the matter:
http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW32
Note the bit right at the bottom about creating Singletons that you can also have other instances.
Thank you Matt – this is just what I needed
[...] actually gain access to my singleton class. Matt Galloway has a great example and tutorial on his blog, but that still didn’t completely help me. I received an “undeclared object” [...]
Excellent post! This is a great guide. I just have one question: when an instance of the singleton class is automatically generated with sharedInstance in one view controller, if another view controller also calls up the class, are they each generating two different instances of the dictionary? Because if so, would that take up a lot of memory?
@Apocryphon – The whole point of a singleton is that it’s the exact same object where ever you reference it from. For this reason, there’ll only ever be one allocated. So, no, it won’t take up lots of memory.
Thank Matt very much.
I learned this blog and created three singleton classes in my iPhone project, two with Protocols and one with many C++ classes instance and methods, they worked very well, now my project is more simple and should be more stable. Thanks.
@Matt
I still believe that from a testability standpoint “strict singletons” are bad. Testability is very important to software design, and without it you can’t prove the code works as intended or works for edge cases.
I use existing testing frameworks, so the way in the which the tests run is unimportant. I have control of the code I write, so I choose to write my code in a manner that is easier to test.
The snippet of code I posted in my previous comment was used to set different instances of the Singleton. However, using that code means that you cannot enforce a “strict singleton,” that prevents more than one allocation.
Using a singleton setter allows my test setup and tear down functions to create a new singleton and cleanup the old one so that there aren’t artifacts from a previous test.
@Paul
I see what you’re saying about the testability of a non-strict singleton, however I’d still argue that it shouldn’t be *testability* that brings you to want to have a non-strict singleton. There’s 2 points that I’d like to use to back that up:
1) If you’re that worried about your own singleton which you control the code for, then you should be worried about other singletons in the OS or other frameworks. You have no control over these and the only way to ensure exact state is maintained between test launches is to completely restart the process.
2) You control the code for the singleton. So surely if you are worried about the singleton not being the same between test launches you should write a unit test for that case. Call your reset function and test that it resets the object functionally back to where it was at the beginning.
I can see the need for non-strict singletons, such as NSFileManager, but it’s also valid to have strict singletons. However, the choice I feel should not come from testability but rather from a functional need.
Hi Matt, Thanks for posting the article. Everything is
working great in my app, but I keep getting these warnings that I’m
not sure how to clear up. The warning is: ‘MyManger’ may not
respond to ‘+sharedManager’ Any ideas?
@David – check you have the .h file included in the file you are calling sharedManager from and also that the MyManager.h has a sharedManager method declared in it.
Matt, I would like to have global variables for two
football teams. However it sounds like you can only instantiate one
copy of a singleton. Any suggestions? Is there a way to create a
global “Team” class?
Thank you Matt for this code..its great! This is the way to communicate between view controllers! Been trying to figure out the right way to do this for some time now..thanks!
Thank you Matt for the code above. I have a doubt, i’ll appericate if u could please clear. In sharedManager you have written
sharedMyManager = [[super allocWithZone:NULL] init];
We have u used super keyword here? If i am writing self in place of super it is struck in loop. Also, when will the copyWithZone method be called or when should we call this method?
Thanks
@Gurpreet – It’s super, because you’re calling the super-class method. That’s right that it’d get stuck in a loop if you replaced super with self – because it’d keep calling itself.
The copyWithZone method is there because you need to override the superclass method so that you can return the same object – as it’s a singleton, so copies don’t make sense.
Thanks Matt, this is great.
As a beginner i got this implemented right away!
There’s only problem i can’t solve.
I have a uitableview which uses sqlite and i use the singleton to check the value of a label and pass it in the singleton. Then there is a database class where i check the singleton var value and parse it in the sql query that filters on the var name using %@ and loads the appropriate data in the next uitableview. This works.
But… if i touch the back button and touch a cell with another label the singleton value is not being updated.
I suspect @property and tried copy, assign, retain etc. but it doesn’t help.
Can you point me in the right direction?
Thanks again.
In reaction to my own previous post. It had nothing to do with the singleton or @property.
Not that i fixed it, but it’s probably something like reloadData for the 2nd tableview.