Search code examples
iosnsuserdefaultsgetter-setter

Objective-C Writing general getter and setter methods


In my project I have a settings class with properties with custom setters that access NSUserDefaults to make everything simpler. The idea is that Settings class has

@property NSString *name

which has custom getter that gets the name value from NSUserDefaults and a setter that saves the new value there. In this way throughout the whole project I interact with the Settings class only to manage user defined preferences. The thing is that it seems way too repetitive to write all the getters and setters (I have about 50 properties), and would like to create one setter and one getter that would work for all variables. My only issue is how to get hold of the name of the variable within the setter.

The final question then is: is it possible to find out within a getter or setter for which property is the function being called?

If you have some other approach I would appreciate it too but considering that I would like to keep all the NSUserDefaults stuff in one class, I can't think of an alternative that doesnt include writing 50 getters and setters.

Thanks!


Solution

  • I found your question very interesting and I said to myself "Challenge accepted!".

    I've created this project on Github.

    Basically, all you have to do is subclass the VBSettings class and then declare de properties, like this:

    @interface MySettings : VBSettings
    
    @property (strong, nonatomic) NSString *hello;
    
    @end
    

    The value of "hello" will be saved to NSUserDefaults with the key "hello". Example of usage:

    MySettings settings = [[MySettings alloc] init];
    settings.hello = "World!"; //The value is saved in NSUserDefaults
    NSLog(@"%@", settings.hello); //The value is restored from NSUserDefaults.