gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:39 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com