简体   繁体   中英

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, eg

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

Why not just add a property :

@property NSMutableDictionary *status;

You can think of a property declaration as being equivalent to declaring two dot-accessor methods.

There is an ongoing discussion about the merits of dot notation vs. message notation . You might want to have a look: Dot notation vs. message notation for declared properties

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM