简体   繁体   English

核心数据和Swift中的计算属性与持久存储

[英]Computed properties vs. persistent storage in Core Data and Swift

I have a feeling this is a silly question, but I'm new to this and I can't find a clear answer. 我有一种感觉这是一个愚蠢的问题,但我是新手,我找不到一个明确的答案。

I have an Activity entity and a Sessions entity. 我有一个Activity实体和一个Sessions实体。 Each Activity can have many Sessions. 每个活动可以有多个会话。 Each Session has a duration attribute. 每个Session都有一个duration属性。

Now I want the average session duration for an activity. 现在我想要一个活动的平均会话持续时间。 Should I add an averageSessionDuration attribute to my Activity entity and update it and persist it when a user adds or deletes a session, or can I just add a computed property to my Activity class and have it calculate the average session duration whenever it's called? 我应该将一个averageSessionDuration属性添加到我的Activity实体并更新它并在用户添加或删除会话时保留它,或者我可以只将一个计算属性添加到我的Activity类并让它计算每次调用时的平均会话持续时间吗?

I guess using a computed property the average session duration would be calculated a little more often than necessary, but I don't know if that matters, does it make a difference in the end? 我想使用一个计算属性,平均会话持续时间会比必要时更频繁地计算,但我不知道这是否重要,它最终是否有所作为?

I don't know what goes on behind the curtains, is fetching every session duration and taking the average a lot more expensive than just fetching an averageSessionDuration property that is updated when necessary and persisted? 我不知道窗帘后面发生了什么,是获取每个会话持续时间并取平均值比仅获取在必要时持续更新的averageSessionDuration属性更昂贵? What are the best practices in this case? 在这种情况下,最佳做法是什么? Is there something else I'm missing? 还有什么我想念的吗?

Thanks in advance, 提前致谢,

Daniel 丹尼尔

It most likely doesn't make any difference in performance but it would be cleaner code (I think) if you use a computed property instead of trying to make sure it's always up to date when you save other values. 它很可能没有任何性能差异,但如果您使用计算属性而不是尝试确保它在保存其他值时始终保持最新,那么它将是更干净的代码(我认为)。

If you are scared of performance issues you can always cache the calculated value every session and just invalidate the cache when you change values in the app. 如果您害怕性能问题,则可以始终在每个会话中缓存计算值,并在更改应用程序中的值时使缓存无效。 That might be the best of two worlds. 这可能是两个世界中最好的。

This is a question of taste and I'm sure there are arguments supporting both sides. 这是一个品味问题,我确信有支持双方的论据。

If you are ever going to fetch on that property then you will want to persist it. 如果您打算获取该属性,那么您将希望保留它。 This is assuming a SQLite store. 这是假设一个SQLite商店。

If you are never going to fetch from it then a computed property is going to be cleaner. 如果你永远不会从中获取,那么计算属性将变得更加清晰。

That is the only question that is important for making that decision. 这是做出决定的唯一重要问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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