实施自己的二传手或使用KVO? [英] Implement own setter or use KVO?

查看:92
本文介绍了实施自己的二传手或使用KVO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,当属性值更改时,我必须在代码中更新一些逻辑,例如:

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){
    [prop release];
    prop = [theProp copy];
    [self myLogic];
  }
}

或:

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
  if ([keyPath isEqualToString:@"prop"]){
    [self myLogic];
  }  
}

哪种方法最好,为什么?

Which is the best way, and WHY?

我非常喜欢第二种方法,因为我不知道编译器会为我生成什么@synthesize指令,因此我选择相信编译器比我的欠款二传手实现更为智能,因此我不会破坏某些内容

I prefect the second way, because I don't know what the compiler will generate @synthesize directive for me, I choose to believe the compiler is more smarter than my owe setter implementation, hence I will not break something.

推荐答案

强悍的通话,恕我直言,这两个选项都很糟糕.

Tough call, IMHO both options suck.

第一个强制您编写自己的设置器,这是很多样板代码. (更不用说,如果您要让相关属性的KVO正常工作,还必须记住还用willChangeValueForKey:didChangeValueForKey:触发KVO通知.)

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

第二个选项也很笨重,您的实现还不够.如果您的超类也有适当的KVO怎么办?您必须在处理程序中的某处调用super.如果没有,您确定您的超类不会改变吗? (有关相关问题的更多有关KVO的信息.)

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

有时候,您可以使用其他方法(例如,绑定(如果使用Mac的话,是Mac操作系统)或简单的通知)(可以发布有关模型已更改且所有相关方都应刷新的通知)来回避问题.

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.");
}];

这将需要更多的工作,但是它将使您的班级完全分开,并且您可以在一个地方解决所有与KVO相关的问题.如果重新计算的属性不足以使其值得使用,我通常会选择第一个解决方案(自定义设置器).

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

这篇关于实施自己的二传手或使用KVO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆