在这个单例类中使用init有什么用?

时间:2013-05-16 10:27:12

标签: iphone ios objective-c singleton

@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

我有一个用于应用程序设置的类。该类还有一个创建singleton和init方法的方法。两者有什么用?我想如果sharedInstance方法在那里,就不需要init ...如果我错了请纠正我.. 任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:7)

init方法是new[self new]调用中被_instance = [[CESettings alloc] init]; 调用的方法。它基本上与

相同
CESettings

但输入次数较少,并且避免对dispatch_once类的名称进行硬编码。

实现单例的更好方法是使用+ (CESettings*)sharedInstance { static dispatch_once_t once; static CESettings *_instance; dispatch_once(&once, ^ { _instance = [self new]; }); return _instance; } ,如下所示:

{{1}}

答案 1 :(得分:3)

来自NSObject的文档:

  

+ (id)new

     

分配接收类的新实例,向它发送一个init   消息,并返回初始化对象。

您在单身创建者方法中调用[self new],然后又会分配一个新实例并向其发送init消息。

答案 2 :(得分:1)

sharedInstance类方法只负责分配和启动一个对象,然后总是返回它。

BUT

你没有经过那种方法,你可以自己调用alloc init,它也可以工作

所以需要init来保持alloc / init应该如何工作的语义