有没有更简单的方法来处理 ios 应用程序中的许多数据更改?
我正在开发一个应用程序,它有许多相互依赖的数据。基本上,我有一组数字字段,用于计算其他数字字段,然后使用这些数字字段计算其他字段。我正在尝试确定处理潜在大量更改的最佳方法。
我想到的一种解决方案是,我可以覆盖用户可以修改的值的设置器来进行计算,然后适当地更新数据对象中的其他值。这样做的最大缺点是需要编写大量(有点样板的)代码。
我想到的另一个解决方案是使用键值观察来处理数据更改,然后更新这些更改的依赖值。请注意,除非独立值更新,否则任何从属值都不会更新。虽然我认为这会更优雅一些,但我担心潜在的性能问题,或者我可能没有考虑到的问题。
我还缺少第三种方法吗?此类工作有最佳实践吗?我知道我可能必须编写一堆某种样板代码 - 我希望这些代码是最容易维护的,并且代码量尽可能最小。
I have an app I am working on, and it has a number of pieces of data that are interdependent. Basically, I have a set of number fields that are used to calculate other number fields, which are then used to calculate other fields. I am trying to determine the best way to handle the potentially large number of changes.
One solution I thought of is that I could override the setters of the values that can be modified by the user to do the calculations and then update the other values in data object appropriately. The largest downside to this is the sheer amount of (somewhat boilerplate) code that needs to be written.
Another solution I thought of is using Key-Value Observing to handle the data changes, and to then update the dependent values from those changes. Note that none of the dependent values will ever update except when an independent value updates. While I think this will be a bit more elegant, I am concerned about potential performance problems, or problems that I am possibly not considering.
Is there a third way that I am missing? Are there any best practices for this type of work? I know that I am likely going to have to write a bunch of boilerplate code of some sort - I would like the code to be the easiest to maintain, and the smallest amount of code possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
KVO 不应该有任何性能问题,除非您有非常多的字段或非常频繁的更新,但它的 API 并不是最好的。一个缺点是它通过单一方法汇集所有通知。这可能是也可能不是问题,具体取决于您的字段数量和类型。
通知也可能是一个不错的选择。每个字段都可以有一个通知名称,它将发布更改,并且其他字段可以在没有指向源字段的显式指针的情况下进行观察。
还有 带有协议的委托,虽然更简单且性能更高,但可能相当繁琐,具体取决于你怎么做的。
KVO shouldn't have any performance issues unless you have very many fields or very frequent updates, but its API isn't the greatest. One downside is that it funnels all notifications through a single method. This may or may not be an issue depending on your number and types of fields.
Notifications might also be a good option. Each field could have a notification name that it would post changes from, and other fields could observe without an explicit pointer to the source field.
There is also delegation with protocols which, while simpler and more performant, can be rather boilerplate-heavy depending on how you do it.