在Singleton中使用自己的setter覆盖属性 [英] Override property with own setter in Singleton
问题描述
我有一个类 ViewController.m
,我想在其中设置其他类 Singleton.m
的属性。它将自动保存到 NSUserDefaults
中。
I have a class ViewController.m
where I want to set a property of my other class Singleton.m
which should automatically be saved to the NSUserDefaults
.
我想我必须将 Singleton.m
中的属性设置为只读并覆盖设置器,但这是最好的办法?如果是,该怎么办?
I think I have to make the property in Singleton.m
readonly and override the setter, but is this the best way? If yes, how do I do that?
推荐答案
将属性设置为只读没有多大意义(如果我了解您的问题正确)。您可能想要的是:
Making the property read-only does not make much sense (if I understand your problem correctly). What you probably want is:
- 覆盖
init
方法以从中加载属性实例化
单例时用户默认值, - 覆盖默认的 setter 以将属性值保存为设置了新值时的用户默认值。
- override the
init
method to load the property from the user defaults when the singleton is instantiated, - override the default setter to save the properties value to the user defaults when a new value is set.
示例: Singleton.h:
#import <Foundation/Foundation.h>
@interface Singleton : NSObject
+(instancetype)sharedSingleton;
@property (nonatomic) BOOL myBoolProp;
@end
Singleton.m:
#import "Singleton.h"
@implementation Singleton
static NSString *kMyBoolPropKey = @"MyBoolProp";
+(instancetype)sharedSingleton
{
static Singleton *sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
-(id)init
{
self = [super init];
if (self) {
_myBoolProp = [[NSUserDefaults standardUserDefaults] boolForKey:kMyBoolPropKey];
}
return self;
}
-(void)setMyBoolProp:(BOOL)myBoolProp
{
_myBoolProp = myBoolProp;
[[NSUserDefaults standardUserDefaults] setBool:myBoolProp forKey:kMyBoolPropKey];
}
@end
(请注意,两者
[[Singleton sharedSingleton] setMyBoolProp:...];
[Singleton sharedSingleton].myBoolProp = ...;
将调用自定义设置方法 setMyBoolProp
。)
will call the custom setter method setMyBoolProp
.)
这篇关于在Singleton中使用自己的setter覆盖属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!