iphone - init 在这个单例类中有什么用..?

标签 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

@实现

//
//  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

我有一个用于应用程序设置的类。该类有一个创建单例的方法和一个 init 方法。两者有什么用..?我想如果有 sharedInstance 方法,就不需要 init 了……如果我错了请纠正我…… 感谢您的帮助。

最佳答案

init 方法是在 [self new] 调用中由 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;
}

关于iphone - init 在这个单例类中有什么用..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16584975/

相关文章:

iphone - "The operation couldn’ t 完成。 ( cocoa 错误 512。)”

ios - 我的快速代码不模拟

iphone - 如何像 [self Method_Name]; 一样使用 self 调用方法;当方法名称很长时 Like -(void)imagePickerController : (UIImagePickerController *)

iphone - 如何通过 Interface Builder 的 XIB 传递 NSManagedObjectContext

iphone - 在 Xcode 4.2 上创建通用应用程序

iphone - 获取 UITableViewCell 文本的正确方法

iphone - 使用 if 语句检查多个应用内购买

javascript - iPad 2 和 iPad 3 网站测试

ios - 没有1309是否可以在中央模式和外围模式下运行?

objective-c - NSXMLParser 忽略节点