Singleton in iOS 5? - objective-c

Hi I had an implementation previous versions of iOS for a singleton as follows:
.h file
#interface CartSingleton : NSObject
{
}
+(CartSingleton *) getSingleton;
.m file
#implementation CartSingleton
static CartSingleton *sharedSingleton = nil;
+(CartSingleton *) getSingleton
{
if (sharedSingleton !=nil)
{
NSLog(#"Cart has already been created.....");
return sharedSingleton;
}
#synchronized(self)
{
if (sharedSingleton == nil)
{
sharedSingleton = [[self alloc]init];
NSLog(#"Created a new Cart");
}
}
return sharedSingleton;
}
//==============================================================================
+(id)alloc
{
#synchronized([CartSingleton class])
{
NSLog(#"inside alloc");
NSAssert(sharedSingleton == nil, #"Attempted to allocate a second instance of a singleton.");
sharedSingleton = [super alloc];
return sharedSingleton;
}
return nil;
}
//==============================================================================
-(id)init
{
self = [super init];
}
However on the web I see people have implemented the Singleton design pattern using this code:
+ (id)sharedInstance
{
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init]; // or some other init method
});
return _sharedObject;
}
Could someone who is experience please guide me.
Im a newbie and thoroughly confused between the old iOS implementation of the Singleton and the new one and which is the correct one?
Thanks a lot

Strictly speaking, you must use:
+ (MySingleton*) instance {
static dispatch_once_t _singletonPredicate;
static MySingleton *_singleton = nil;
dispatch_once(&_singletonPredicate, ^{
_singleton = [[super allocWithZone:nil] init];
});
return _singleton;
}
+ (id) allocWithZone:(NSZone *)zone {
return [self instance];
}
Now you guarantee that one cannot call alloc/init and create another instance.
Explanation: The instance method is at the class level and is your main access method to get a reference to the singleton. The method simply uses the dispatch_once() built-in queue that will only execute a block once. How does the runtime guarantee that the block is only executed once? Using the predicate you supply (of type dispatch_once_t). This low-level call will guarantee that even if there are multiple threads trying to call it, only one succeeds, the others wait until the first one is done and then returns.
The reason we override allocWithZone is because alloc calls allocWithZone passing nil as the zone (for the default zone). To prevent rogue code from allocating and init-ializing another instance we override allocWithZone so that the instance passed back is the already initialized singleton. This prevents one from creating a second instance.

The dispatch_once snippet is functionally identical to other one. You can read about it at http://developer.apple.com/library/mac/#documentation/Darwin/Reference/Manpages/man3/dispatch_once.3.html.
This is what I use for singletons:
+ (MySingleton*) getOne {
static MySingleton* _one = nil;
#synchronized( self ) {
if( _one == nil ) {
_one = [[ MySingleton alloc ] init ];
}
}
return _one;
}
NOTE: In most cases, you do not even need to use #synchronized (but it is safe this way).

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.
Please check a link with best answer
:http://www.idev101.com/code/Objective-C/singletons.html

Related

Objective C Singleton - Prevent Allocating Memeory More than Once

I use a sinlgeton in my application for managing data that is available to the whole application, which accessed via:
static MMProductManager *sharedInstance = nil;
+(MMProductManager*)SharedInstance {
dispatch_once( &resultsToken, ^(void) {
if ( ! sharedInstance ) {
sharedInstance = [[MMProductManager alloc] init];
}
});
return sharedInstance;
}
Everything is working as expected.
In Objective C, there does not seem to be a way to hide any object's init method, and in my case having more than instance of MMProductManager would lead to data being duplicated (in the best case scenario).
What I would like to do is guard against instantiating more than one instance. Other languages seem to have this feature; i.e. marking certain methods/classes as private. I am thinking of implementing something along like:
-(id)init {
// guard against instantiating a more than one instance
if ( sharedInstance )
return sharedInstance;
if ( (self = [super init]) ) {
self->_resultsQueue = dispatch_queue_create( kMMResultQLAbel, NULL );
self->_initialized = FALSE;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(handleNotification:)
name:UIApplicationDidReceiveMemoryWarningNotification
object:0];
[self initialize];
}
return self;
}
Does this approach seem reasonable?
What would happen in the case of someone allocating this class, then calling the init described above? Would it be reasonable to override +(id)alloc? If so How would I go about doing that?
I know the convention of exposing a SharedInstance method is an implicit message to other developers to go through this method, but I would like a bit more control if possible.
You don't want to override - init (if not for some other reason) - - init is not the method that creates the instance. You want to override + alloc for this:
#implementation SingletonClass
+ (id)alloc
{
static id instance = nil;
if (instance == nil) {
instance = [super alloc];
}
return instance;
}
#end
This way you can actually prevent (almost) completely creating multiple instances of SingletonClass.
(Unless somebody falls back to calling
id trickyDifferentInstance = class_createInstance(objc_getClass("SingletonClass"), 0));
but that's very unlikely.)

Singletons objective C

I have a NSString *date. I fetch some data from the internet and now I have the date I want in this variable. I want to be able to use this NSString at anytime without calling a method that returns it at any scope within my program.
Where would I put the code to retrieve the date from the internet that the variable will hold? Would it be here? and then would I eventually make date= sharedInstance?
static SingletonClass *sharedInstance = nil;
// Get the shared instance and create it if necessary.
+ (SingletonClass *)sharedInstance
{
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
}
//Do I Put Code here?????
return sharedInstance;
}
Thanks in advance!
If you really want to use a singleton pattern and can target an OS with GCD, then dispatch_once can simplify your singleton code, e.g.
+ (id)sharedFoo
{
static dispatch_once_t pred;
static Foo *foo = nil;
dispatch_once(&pred, ^{ foo = [[self alloc] init]; });
return foo;
}
Depending on your requirements, you can override the init method to provide whatever additional initialization you need.

Setting static inside its method call (with singleton pattern)

is smth. like this legit? it compiles and looks running ok, but is it ok? (aim setting myself to nil, inside my method)
i mean iam setting myself static to nil, in a method
static MyClass * StaticInstance = nil;
+ (MyClass *) sharedStaticInstance
{
if (StaticInstance == nil) {
StaticInstance = [[MyClass alloc] init];
}
return StaticInstance;
}
- (void) killStaticSelf
{
StaticInstance = nil;
}
and later
[[MyClass sharedStaticInstance] doSmth]; // our static instance is created
[[MyClass sharedStaticInstance] killStaticSelf]; // now its killed inside itself method
[[MyClass sharedStaticInstance] doSmth]; // now it should recreate again
Its having a memory leak.
You should dealloc the StaticInstance first and then you should assign nil to it.
Yes, that's how it's done. I use the sharedStaticInstance often, though I don't usually create a destructor it's probably a good idea, as long as all references to the shared instance in this class pass through sharedStaticInstance first.
EDIT: I just noticed that killStaticSelf is an instance method - it should be a class method I believe, but there shouldn't be any issue either way.
[MyClass killStaticSelf];
Even as the function stack closes, since sending messages to nil doesn't cause issues in Objective-C.
your sharedInstance method is not thread safe so you could get a race condition in this code:
if (StaticInstance == nil) {
StaticInstance = [[MyClass alloc] init];
}
- (void) killStaticSelf
{
StaticInstance = nil;
}
the above code has a leak since you do not provide StaticInstance as a retain property (apparently). You could instead wrap your singleton code in a property but that uses the same static instance.
It's legit, but you need to release the variable before setting it to nil, to avoid memory leaks if you're not using ARC.
Though comprehension of such singleton usage logic is beyond my humble brain abilities.

When and where to release a Singleton instance in Objective-C?

I am not sure if i am asking the right question or not.
I have a singleton class as below:
static DBHandler *dbHandler = nil;
+(DBHandler *)sharedDBHandler {
#synchronized(self) {
if(nil == dbHandler) {
dbHandler = [[[self class] alloc] init];
}
}
return dbHandler;
}
When and where to release a Singleton instance in Objective-C ?
Thanks,
Never and Nowhere. Unless in the code that uses the singleton object you retained it for some inexplicable reason.
Most often they are located in static memory which means they are handled differently. See this question:
Objective-C/iPhone Memory Management Static Variables

Objective-C Singletons and LLVM/clang leak warnings

I'm using the singleton pattern in several places in an application, and I'm getting memory leak errors from clang when analyzing the code.
static MyClass *_sharedMyClass;
+ (MyClass *)sharedMyClass {
#synchronized(self) {
if (_sharedMyClass == nil)
[[self alloc] init];
}
return _sharedMyClass;
}
// clang error: Object allocated on line 5 is no longer referenced after this point and has a retain count of +1 (object leaked)
I'm using these settings for scan-build:
scan-build -v -v -v -V -k xcodebuild
I'm fairly certain that the code in the singleton is just fine - after all, it's the same code referenced here on Stack Overflow as well as in Apple's documentation - but I would like to get the memory leak warning sorted out so my scan-build returns success.
I may be being exceptionally dense, but surely your line 5
[[self alloc] init];
allocates an object of the containing class type, and promptly throws it away? Do you not want
_sharedMyClass = [[self alloc] init];
?
Apple has since updated their recommended singleton code to pass the static analyzer:
+ (MyGizmoClass*)sharedManager
{
if (sharedGizmoManager == nil) {
sharedGizmoManager = [[super allocWithZone:NULL] init];
}
return sharedGizmoManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [[self sharedManager] retain];
}
Now +sharedManager calls super's -allocWithZone: and assigns the return of -init, and the singleton's -allocWithZone: just returns a retained sharedInstance.
Edit:
Why the retain in +allocWithZone:?
+allocWithZone: is overridden because someone using MyGizmoClass could circumvent the singleton by calling [[MyGizmoClass alloc] init] instead of [MyGizmoClass sharedManager]. It's retained because +alloc is expected to always return an object with a retain count of +1.
Every call to +alloc should be balanced with a -release or -autorelease, so without the retain in +allocWithZone:, the shared instance could potentially be deallocated out from under other users.
You may be interested in a simple, one-method, GCD-based singleton implementation (and thus 10.6+ only) posted on Mike Ash's site:
+ (id)sharedFoo
{
static dispatch_once_t pred;
static Foo *foo = nil;
dispatch_once(&pred, ^{ foo = [[self alloc] init]; });
return foo;
}
You are referencing self in a class method! Big no-no! Secondly, you are calling [[self alloc] init] and just throwing away the instance. You should assign the singleton reference in the class method, and not in init like I am guessing you are doing. Next, there is no real guarantee that _sharedMyClass will be initialized to zero. You should explicitly initialize it to nil.
static MyClass *_sharedMyClass = nil;
+ (MyClass *)sharedMyClass {
#synchronized(self) {
if (_sharedMyClass == nil)
_sharedMyClass = [[MyClass alloc] init];
}
return _sharedMyClass;
}
You also probably had this in there too...
+ (id)allocWithZone:(NSZone *)zone {
#synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [super allocWithZone:zone];
return sharedInstance; // assignment and return on first allocation
}
}
return nil; // on subsequent allocation attempts return nil
}
The reason you weren't storing it in init is because you were storing it in the method that alloc called. This is the pattern Apple has in their examples. If you save the value in your init as well, all is fine and the warning goes away. I'd leave the allocWithZone implementation alone.