Objective-C singleton pattern in iOS 5+ - ios

I've been reading a lot of threads and blog articles about how to implement a singleton in objective-c, several of them maybe being a bit deprecated (year 2010 or earlier), and it seems like people have different opinions regarding this issue... Does Apple have documentation about implementing a singleton? I couldn't find it. If so, could somebody tell me where?
I need a singleton for a class that has some both public and private variables. Currently, this is the implementation I have for such class:
#interface MySingleton ()
#property (strong, nonatomic) NSString *state;
#end
#implementation MySingleton
#synthesize state = _state;
#synthesize count = _count;
static MySingleton *sharedObject = nil;
+ (MySingleton *)sharedInstance
{
static dispatch_once_t _singletonPredicate;
dispatch_once(&_singletonPredicate, ^{
sharedObject = [[super allocWithZone:nil] init];
});
return sharedObject;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [self sharedInstance];
}
Should be this the recommended way? And how should I initialize the instance variables, public and private?
Another issue I'd like to make clear about singleton is: will this generate a memory leak? Is the use of singletons actually recommended in iOS?
Thanks

The above is correct, along with #miho's comment about includng the static object inside of the sharedInstance method. But there is no reason to override +allocWithZone:. Singletons in ObjC are generally "shared," not forced. You're free to create other instances of a "singleton." If it's illegal to create other instances, then you should make init perform an NSAssert rather than fooling the caller in +allocWithZone:. If your singleton is mutable (and most are), you absolutely should not override +allocWithZone: this way.
Another issue I'd like to make clear about singleton is: will this generate a memory leak?
No. This object will never be released, but it will always be accessible. That is not a leak.
Is the use of singletons actually recommended in iOS?
Yes, and it is a very common pattern, used all over the Cocoa frameworks. That said, there are various other patterns that have started to recently become somewhat popular among developers. Dependency Injection is getting some interest, though I don't see it in practice very often. Reducing your reliance on singletons can improve testability, and I have been experimenting recently with how to eliminate some of them in my code with some success. But they have a long, proud history in Cocoa, and I do not consider them a problem.
EDIT: you have one actual bug in your code. You should be calling [[self alloc] init], not [[super alloc] init]. There's no reason to ever call +allocWithZone:, just use +alloc. (The time when ...WithZone: methods were useful has long passed.)

In Xcode, under 'Search Documentation' enter Creating a Singleton Instance. There are lots of results (but the link above, at the bottom of the page, has example code).

Yes, this is the recommended way. There is only one small difference of how I use it: I define the sharedObject as static variable inside the + (MySingleton *)sharedInstance method, because it shouldn't be possible to access the variable from anywhere else then from the getter method.
And no, you won't create a memory leak. When your app is terminated all reserved memory used by your app will be released anyway and there is no other situation where a static shared instance should get released. In pre-ARC area it even was common to override the release method do prevent accidentally releasing of the object.

A bit of warning using gcd for singletons:
dispatch_once(&_singletonPredicate, ^{
sharedObject = [[super allocWithZone:nil] init];
});
if the init method for some reason addresses the singleton object directly or indirectly, there will be a deadlock. For this reason I believe that the more appropriate way to write a singleton is through the
+ (void) initialize
method

I am still using the singleton header thingy from CocoaWithLove - may be a bit dated but still works like a charm. It basically does the same as described here referring to Apples documentation and I would assume at least Apple's documentation (bottom of this page) is still valid. There are people assuming it will stay valid indefinitely sine it is the official solution Apple suggested.

Related

Objective C - Creating singleton using shared instance

I have doubts regarding the creation of singleton class in Objective-C/iOS.
Where ever I see the trick to create a singleton class in objective-C is this code
+ (id)sharedManager {
static MyManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
Whenever I call [MyManager sharedManager] of course I get the same address. However, I can also write [MyManager new] in which case the address is different.
1.Isn't the concept of singleton class is that it restricts the instantiation of a class to one object?
2.If we can create another object its not a singleton anymore, is it?
In my iOS app I tried [UIApplication new]. I got an exception in runtime. Now this I get. You cannot make another instance of UIApplication since its a singleton class.
So why the use of shared instance considered to be the way of creating a singleton class or have I got this all wrong?
The sharedManager is the convenience method you'd use to access the singleton instance. While this doesn't guarantee that there will be only one instance of that manager over the app, if everyone is using sharedManager then there will practically exist only one instance of that manager.
This kind of singletons are singletons by convenience, not by implementation. You should use them, for multiple reasons:
you can unit test them, by calling alloc init in your unit tests and making use of that brand new allocated object
it makes your life easier if decide to later refactor the manager and no longer use it as a singleton if you consider it from the begging like a regular object to work with
Of-course, you can make a singleton by-the-book by overriding the init and allocWithZone: to either return the only instance or by raising an exception, however I'm not sure they'd worth the effort.
There's a very good tech talk regarding singletons held by Misko Hevery in the Google clean code talks playlist, the link to the video: here. This kind of singletons are referred as lower case S singletons, not capital S ones in the video, and Misko explains very well why they are preferred.
It doesn't break singleton concept. You choose your way to implement what you want. If you want to create only singleton instance, you can make run error by override init function:
[NSException exceptionWithName:NSInternalInconsistencyException
reason:#"bla bla bla..." userInfo:nil];
or
you can override it to force return to shared instance.
Of course, you can. But it not recommend if you are using singleton.
Objective-C uses a pragmatic approach. Your +sharedManager method returns a singleton. If someone is stupid enough to call [SingletonClass new] or [[SingletonClass alloc] init], that's their problem. They'll get what they deserve. There is no reason to prevent people from shooting themselves in the foot if that is what they want to do.
There are millions of programming errors that people can make and that the developer of a class or the compiler cannot prevent. No point wasting effort on preventing this particular error.

What is the alternative way for Singleton

I have a single ton which is working fine, but i don't want to use singleton instead any alternative best way
find my code for reference
Myclass.h
+ (instancetype)shareInformation;
Myclass.m
+ (instancetype)shareInformation
{
static Myclass *manager;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[Myclass alloc] init];
});
return manager;
}
MyNextClass.m
[[Myclass shareInformation] methodofMyclass:^(NSDictionary *results, NSError *error) {
//my code
}];
i have a class Myclass in which i am using a singleton to init manager = [[Myclass alloc] init]; and i am calling this in other class MyNextClass but i don't want to do this in this way i mean i don't want to use singleton pattern i need some this alternative for what i do here
I'm guessing you want to avoid using the singleton as it's considered an anti-pattern.
A solution would be to use a dependency injection container to wire up your application and configure it to resolve your object as a single instance.
I'm not familiar with ios development but Typhoon looks like popular choice.
You can use a singleton or you can use a normal instance, it's up to you. One of the major benefits of a singleton is so that you can get a reference to it anywhere without difficulty.
You could always create a class, and pass a reference of it anywhere you want to use it. For example in your view controller you create it, make sure you create a property of it in your following view controllers and then pass that same reference to the new view controller.
It's best to use a singleton if that's what you're trying to accomplish and you only need one instance though.
Another option, for "global" data, is to make use of the AppDelegate. You can place simple properties in the AppDelegate itself, or define a property (or explicit "getter" method) which returns a pointer to some more complex "global" object.
Note that using the AppDelegate this way is considered "bad form" by many, but there's really not that much bad about it, other than accessing the AppDelegate itself is a bit awkward. (And it upsets the sensibilities of those who are sure they know what "separation of concerns" really means.)

Should we create more than one object for a singleton class? is this fine for singleton design pattern [duplicate]

This question already has answers here:
What should my Objective-C singleton look like? [closed]
(26 answers)
Closed 9 years ago.
I have created a singleton class, And Here is code
static DPGameManager *sharedManager = nil;
+ (DPGameManager *)sharedManager
{
static dispatch_once_t singletonPredicate;
dispatch_once (&_singletonPredicate, ^(){
sharedManager = [[DPGameManager alloc]init];
});
return sharedManager;
}
DPGameManager *m1 = [DPGameManager sharedManager];
DPGameManager *m2 = [DPGameManager alloc]init];
DPGameManager *m3 = [DPGameManager alloc]init];
m1, m2, m3 are three different objects.
But we should not be able to create three different object for a singleton class.
How can we achieve this.?
Or is This fine to create different object for a Singleton class.
First of all: A singleton is a class of which you can create one and only one instance object. This is the usual definition and it is the definition that Apple uses. But, funny thing, in the same documentation the examples contains cases, in which this rule is not fulfilled. (I. e. NSFileManager IIRC.) So in Apple's opinion there is not big difference between shared instances and singletons even there is a difference. (Shared instances are "special instances", singletons are lonesome cowboys.)
So – maybe – it is good enough to adopt this "shared instances are singletons even they are not" antipattern. I wouldn't do that. But probably nobody would even think of +alloc, when he finds a method called +sharedInstance. So – again maybe – it is no big deal.
While it has been very easy to adopt the singleton pattern with manual RC, it became a little bit harder with automatic RC. I think the easiest way is to return sharedInstance in -init… as mentioned in the comments. -init… methods are ownership consuming and ownership transferring. (This is not mentioned in Apple's documentation. You should always read the clang docs for this subjects. They are better by far.) So the old instance delivered by +alloc will be consumed and move away.

Static Class vs Singleton [duplicate]

This question already has answers here:
Singleton Instance vs Class Methods
(2 answers)
Closed 9 years ago.
So, pretty simple question. Ignoring the implications of over-use of the singleton pattern. I'm trying to find a reliable singleton patter in Objective-C. I have come across this:
#implementation SomeSingleTonClass
static SomeSingleTonClass* singleInstance;
+ (SomeSingleTonClass*)getInstance
{
static dispatch_once_t dispatchOnceToken;
dispatch_once(&dispatchOnceToken, ^{
singleInstance = [[SomeSingleTonClass alloc] init];
});
return singleInstance;
}
- (void)someMethodOnTheInstance
{
NSLog(#"DO SOMET WORK")
}
#end
This I am fairly happy with but it leads to a lot of this:
[[SomeSingleTonClass getInstance] someMethodOnTheInstance];
My question is, why is this better than a purely static class.
#implementation SomeStaticClass
static NSString* someStaticStateVariable;
- (id)init
{
//Don't allow init to initialize any memory state
//Perhaps throw an exception to let some other programmer know
//not to do this
return nil;
}
+ (void)someStaticMethod
{
NSLog(#"Do Some Work");
}
All you really gain, is mildly cleaner looking method calls. Basically you swap out this:
[[SomeSingleTonClass getInstance] someMethodOnTheInstance];
For this
[SomeStaticClass someStaticMethod];
This is a minor simplification for sure, and you can always store the instance within your class. This is more intellectual curiosity, what Objective-C god am I pissing off by using static classes instead of singletons? I'm sure I can't be the first person to think this, but I promise, I did a duplicate search first. The few answers I found, I felt like were based on older versions of cocoa, because even the discussed singleton patterns seemed to suffer from threading issues.
Static class : Used when you want to group together utility methods that are state independent.
Singleton : Used when you have multiple methods that share a state.
I've found it convenient to do a mix of both. I use a standard singleton pattern similar to your first that results in:
[[MyClass defaultInstance] doSomething];
But I also want to be able to create other instances of the same class:
MyClass *secondInstance = [[MyClass alloc] init];
[secondInstance doSomething];
When I want more concise access to call methods on the singleton instance, I define class methods as follows:
// class method to call a method on the singleton instance
+ (void)doSomething
{
[[MyClass defaultInstance] doSomething];
}
So with that, I can use:
[MyClass doSomething];
You're pissing off no Objective-C gods with a class like that. Actually, Apple recommends to use that pattern in some cases (I think they mentioned this in one of the ARC session videos, where they discussed common design patterns and how to implement them using ARC).
In other cases, where you can have multiple instances of a class, but want a default one, you'll of course have to use the shared instance approach.
The first example seems to be needlessly creating a singleton-like instance of a class. I say needlessly because from your other comments it appears that the class doesn't declare any properties or instance variables. Given that the fundamental purpose of an object is to provide storage for state, an object with no instance variables is rarely a useful thing.
Your second example shows a class that would never be instantiated. Again, the fundamental purpose of a class in Objective-C is to act as a factory for instances, so a class that's never instantiated isn't really useful or necessary.
Instead, you can just provide a set of C functions. C functions don't need to be associated with a class at all. So consider doing something like this:
static NSString* someStaticStateVariable;
void someFunction(void)
{
NSLog(#"Do Some Work");
}
The functions can be in separate .h/.m pair, or can be incorporated in the .h/.m for an existing class if it makes sense to do so (generally, if the functions are closely associated with the concerns of that class).

Proper retention of object using NSObject load method

I'm not quite sure where I'm going wrong with this implementation and what adjustment I need to make so that the loaded singleton stays in memory.
#implementation ApplicationSettings
static ApplicationSettings *sharedSettings = nil;
+ (void)load
{
#autoreleasepool {
sharedSettings = [self sharedSettings];
[self configureInitialSettings];
}
}
+ (ApplicationSettings*) sharedSettings {
if (sharedSettings)
return sharedSettings;
else {
return [[[ApplicationSettings alloc] init] autorelease];
}
}
- (void) dealloc {
[super dealloc];
}
The main methods for loading are shown here, along with the dealloc (I'm not using ARC).
I have started using this pattern recently. I'm going to have to check each implementation to make sure it's right. I found one case where it is being deallocated and causing a crash. Obviously the #autoreleasepool owns it. Should I remove the autorelease in the return statement so it doesn't go into the autorelease pool? If I do that, then it's retained until the program is killed, which is fine with me. Is there anything wrong with that?
That's not the correct way to declare a singleton class. (And as a result, your +load method and object retention does not fit with your usage here, and the reason of your crash)
Loading the singleton instance in the +load method is useless, as it is best to allocate the instance only when needed, that is when it is first requested (lazy loading)
But more important, returning an autoreleased instance in the sharedSettings method make the singleton pattern invalid and fail its purpose, as you return an instance that will be released as soon as the autorelease pool will be drained (that is at the end of the current RunLoop iteration -- if not sooner if you have any inner #autoreleasepool used). That's very likely to be the cause of your crash!
The implementation of dealloc is useless, first because it only call its super implementation (so you can avoid the whole method definition), and because as your class is meant to be a singleton, the instance will never be released from memory while your app is alive.
And last but not least, your implementation is not thread-safe at all.
Of course, normally you need to balance alloc and init calls with release or autorelease calls. That's the main rule of memory management. But for the Singleton Pattern, as per definition the shared instance of a singleton lives as long as the application live (that's is main role), this is the exception to the rule, and you should not release your sharedInstance that holds your singleton object, to make sure it keeps living and is not deallocated from memory.
One correct (legacy) implementation for a singleton without ARC would be to overload the alloc/retain/release/autorelease/retainCount methods, as explained in the Apple documentation about singleton. But in fact that's not really the way we do it anymore these days, as this documentation is quite old (was written before GCD existed) and obsolete, and as GCD now offers a way better alternative, that is guarantied to be thread-safe, and is compatible with both non-ARC and ARC too (whereas the latter is not possible to implement under ARC environment). So here it goes:
#implementation ApplicationSettings
+(ApplicationSettings*)sharedInstance
{
static ApplicationSettings* sharedInstance = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{ sharedInstance = [[self alloc] init]; });
return sharedInstance;
}
#end
And that's all. No need for a global variable outside of the method or whatsoever. Simply declare this method and use it every time you need access to the singleton and you're done.
And if you need to fill some instance variables of your singleton then, like what you probably do in your configureInitialSettings method, simply do it in the init method of your singleton, as you would do in a standard class as usual.
Additional Note: If you want to be really strict, some may argue that it will not forbid the allocation/creation of other instances of the class using alloc/init (and neither do your own implementation in your question) so that is not a real singleton: one can still allocate multiple instances of it if s/he really wants to.
But in practice even if that's true, I don't see any reason why to really add these constraints (and if you switch to ARC one day, you can't add these constraints anyway). What you really want when you seek for the Singleton Pattern is more "a common instance shared accross the whole application" than "a way to forbid the creation of multiple instances", and that's what we have here. And actually that's the case for most of the classes that claim to be Singletons (like NSFileManager for example).

Resources