Implement own setter or use KVO?

后端 未结 3 1067
臣服心动
臣服心动 2021-02-07 22:22

In short, when the property value changing, I have to update some logic in my code, for example:

- (void)setProp:(NSString *)theProp
{
  if (prop != theProp){
           


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-02-07 22:59

    Tough call, IMHO both options suck.

    The first one forces you to write your own setter, which is a lot of boilerplate code. (Not to mention that you have to remember to also fire KVO notifications with willChangeValueForKey: and didChangeValueForKey: if you want KVO for the property in question to work.)

    The second option is also quite heavy-weight and your implementation is not enough. What if your superclass also has some KVO in place? You’d have to call super somewhere in the handler. If not, are you sure your superclass won’t change? (More about KVO in a related question.)

    Sometimes you can sidestep the issue using other methods like bindings (if you’re on a Mac) or plain notifications (you can post a notification that a model changed and all interested parties should refresh).

    If you have many recalculations like this and can’t find any better way around, I would try to write a superclass with better observing support, with interface like this:

    [self addTriggerForKeyPath:@"foo" action:^{
        NSLog(@"Foo changed.");
    }];
    

    This will take more work, but it will keep your classes cleanly separated and you can solve all KVO-related problems on one place. If there are not enough recalculated properties to make this worthwile, I usually go with the first solution (custom setter).

提交回复
热议问题