Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 704
Ankit Srivastava Avatar asked Dec 05 '25 10:12

Ankit Srivastava


1 Answers

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;
}
like image 89
Sergey Kalinichenko Avatar answered Dec 07 '25 00:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!