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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With