Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a dynamic/computed property in iOS 7

Having just started doing iPhone programming with iOS 7, I find properties difficult to grasp past the simple. It's difficult to discern what is relevant, and what is no longer relevant as one discovers documentation about them (official or otherwise), since things have evolved over the last few releases.

I get the basic patterns, e.g.

@property (strong, nonatomic) NSString *name;

I know I should refer to _name if I want to do direct access, but having done the property, I can/should do self.name, and that that will turn into things like [self setName: ...] or [self name] and that I can even implement these to create side effects, and that I get KVO behavior from them.

The new ground I wanted to venture into today, was having a virtual property, so that I can use dot notation when accessing/setting, but that I will define the access/set methods. More specifically, I have an object with the following "normal" properties:

@property (strong, nonatomic) NSDate* started;
@property (strong, nonatomic) NSDate* paused;
@property (assign, nonatomic) BOOL repeat;

I want to add a status property that will return/assign an NSDictionary derived from those values. The "methods" part I get how to write:

- (NSMutableDictionary*) status {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if (self.started != nil)
        dict[@"started"] = self.started;
    if (self.paused != nil)
        dict[@"paused"] = self.paused;
    if (self.repeat)
        dict[@"repeat"] = @(YES);
    return dict;
}

and

- (void) setStatus: (NSDictionary*) doc {
    self.started = doc[@"started"];
    self.paused = doc[@"paused"];
    self.repeat = doc[@"repeat"] != nil;
}

What I don't know, is what magic sauce I add where, so that I can just use self.status and self.status = @{}? In iOS 7 / Xcode 5. I don't need this virtual/composite property to be KVO'able.

like image 967
Travis Griggs Avatar asked Dec 02 '22 16:12

Travis Griggs


1 Answers

Just add

@property (strong, nonatomic) NSDictionary* status;

to the interface. Since you have implemented both setter and getter for the property, the compiler with not create any accessor methods (and no backing instance variable _status), and your methods are called.

like image 55
Martin R Avatar answered Dec 17 '22 00:12

Martin R