Override property with own setter in Singleton [cl

2019-09-16 19:03发布

问题:

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.

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?

回答1:

Making the property read-only does not make much sense (if I understand your problem correctly). What you probably want is:

  • 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.

Example: 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

(Note that both

[[Singleton sharedSingleton] setMyBoolProp:...];
[Singleton sharedSingleton].myBoolProp = ...;

will call the custom setter method setMyBoolProp.)