处理 CoreData
managedObjectContexts
的首选方式是什么?为什么?
我经常看到三种不同的方式,以及一种额外的方式:
- 在
AppDelegate
中声明并让 View Controller 依赖于AppDelegate - 一个
sharedManager单例类
每个 View Controller 上的属性
并让父 View Controller 设置它UIViewController 的
类别
,公开共享的manageObjectContext
。
您认为每种方法的优缺点是什么?
最佳答案
Declare in
AppDelegate
and let the view controller depend on theAppDelegate
恶心。应用程序委托(delegate)不应参与,因为数据模型不是应用程序级别的委托(delegate)事件。所有其他类都依赖于应用程序委托(delegate)也是不合适的。
Apple 在示例代码中采用此选项是因为它很简单,但这并不意味着它就是正确的。
A sharedManager singleton class
提供良好的知识管理、放置迁移逻辑的良好位置(如果需要在映射模型之外),并且可以将整个应用程序从应用程序中的任何远程同步方面抽象出来。
很多人不喜欢单例(全局状态),但它们确实有其用处。
Property on each view controller and let the parent view controller set it
非常好 - 但取决于(根)父级首先从哪里获取 MOC。
A category for
UIViewController
that expose the shared manageObjectContext
同样,取决于 MOC 的来源。这比在整个代码中显式引用更好地隐藏了知识,但与错误的类的交叉耦合仍然很糟糕。
关于ios - CoreData - 对 ManagedObjectContext 使用 AppDelegate、单例或 View Controller 上的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22146163/