Ankit Srivastava
Ankit Srivastava

Reputation: 12405

What is the use of init in this singleton class..?

@Interface

//
//  Created by macbook on 31.05.12.
//
// To change the template use AppCode | Preferences | File Templates.
//


#import <Foundation/Foundation.h>


@interface CESettings : NSObject
+ (CESettings *)sharedInstance;

- (void)save;
@end

@Implementation

//
//  Created by macbook on 31.05.12.
//
// To change the template use AppCode | Preferences | File Templates.
//


#import "CESettings.h"

@interface CESettings ()
@property(nonatomic, strong) NSUserDefaults *userDefaults;
@end

@implementation CESettings
@synthesize userDefaults = _userDefaults;

#pragma mark - Singleton
static CESettings *_instance = nil;
+ (CESettings *)sharedInstance {
    @synchronized (self) {
        if (_instance == nil) {
            _instance = [self new];
        }
    }

    return _instance;
}

- (id)init {
    self = [super init];
    if (self) {
        self.userDefaults = [NSUserDefaults standardUserDefaults];
    }

    return self;
}

#pragma mark - Methods
- (void)save {
    [self.userDefaults synchronize];
}

@end

I have a class used for settings in an app. The class has a method for creating singleton and an init method as well. What is the use for both..? I think if the sharedInstance method is there , there is no need for the init... please correct me if I am wrong.. Any help is appreciated.

Upvotes: 2

Views: 205

Answers (3)

Daij-Djan
Daij-Djan

Reputation: 50099

the sharedInstance class method is only responsible for allocating and initing ONE object and then always returning that.

BUT

you dont have go through that method you can call alloc init yourself and it will also work

so init is needed to keep the semantics of how alloc/init should work

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

The init method is what gets called by new in the call of [self new]. It is essentially the same as

_instance = [[CESettings alloc] init];

but takes less typing and avoids hard-coding the name of the CESettings class.

A better way of implementing singleton is using dispatch_once, like this:

+ (CESettings*)sharedInstance
{
    static dispatch_once_t once;
    static CESettings *_instance;
    dispatch_once(&once, ^ { _instance = [self new]; });
    return _instance;
}

Upvotes: 7

DrummerB
DrummerB

Reputation: 40211

From the documentation of NSObject:

+ (id)new

Allocates a new instance of the receiving class, sends it an init message, and returns the initialized object.

You're calling [self new] in your singleton creator method, which in turn will allocate a new instance and send it an init message.

Upvotes: 3

Related Questions