@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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With