Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 278
Denis Balko Avatar asked Jan 05 '23 15:01

Denis Balko


1 Answers

Another approach could be this. No properties, just key value subscript.

@interface DBObject : NSObject<NSCoding>
+ (instancetype)sharedObject;
@end

@interface NSObject(SubScription) 
- (id)objectForKeyedSubscript:(id)key;
- (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key;
@end

On the implementation file:

+ (instancetype)sharedObject {
   static DBObject *sharedObject = nil;
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
     sharedObject = [[DBObject alloc] init];
   });
   return sharedObject;
}

- (id)objectForKeyedSubscript:(id)key {
   return [[NSUserDefaults standardUserDefaults] objectForKey:key];
 }

- (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key {
   [[NSUserDefaults standardUserDefaults] setObject:obj forKeyedSubscript:key];
   [[NSUserDefaults standardUserDefaults] synchronize];
 }

Now, you can use it like this:

 // You saved it in NSUserDefaults
[DBObject sharedObject][@"name"] = @"John"; 

// You retrieve it from NSUserDefaults
NSLog(@"Name is: %@", [DBObject sharedObject][@"name"]); 

I this this is the best approach and is what i will use in the future.

like image 155
Harald Avatar answered Jan 15 '23 04:01

Harald