开发者

Objective-C - Is there a way to "override" dot syntax?

Take for example the following:

Project *project = [[Project alloc] init];
project.title = @"MyProject";
project.field = @"SomeOtherField";

I want to set a flag whenever a property is changed. Is there any way this can be done when the property changed is done开发者_C百科 via dot syntax?

I could just overwrite

- (void) setValue:(id)value forKey:(NSString *)key

And set the object properties using KVC:

[project setValue:@"SomeOtherField" forKey:@"field"];

But the dot syntax always looks cleaner ;)

Thanks!


Use Key-Value Observing if you will be doing this with more than one property/object.

Register as an observer:

[project addObserver:self
          forKeyPath:@"title"
             options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOldKey)
             context:NULL];

Implement the change handler

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
   if ([object isKindOfClass:[Project class]] && [keyPath isEqual:@"title"]) {
       //do something with [change objectForKey:NSKeyValueChangeNewKey];
   }

   [super observeValueForKeyPath:keyPath
                        ofObject:object
                          change:change
                         context:context];
}


The dot syntax obj.var=x is converted to [obj setVar:x]. So to override the dot is achieved creating the method -(void) setVar:...

I do it a lot.


When using properties, you could have setTitle and it work with project.title.

- (void) setTitle:(NSString *)title;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜