Passing managedObjectContext along to view/controller hierarchy

感情迁移 提交于 2019-12-20 02:56:32

问题


Managed object context in most cases created in application delegate. What are the ways of passing it along to view/controller hierarchy, so every navigation/tab controller in the tree can have access to it. Passing it every time from parent to child may not be the best since I have to carry this information every time and sometimes not all of the controllers to the way of particular child may need it.


回答1:


The recommended design is to do a dependency injection. This means that when you create a UIViewController you pass in the NSManagedObjectContext via a property. If the UIViewController only needs a single or set of NSManagedObject instances then you would just hand those in via properties.

This design is more flexible and allows for greater reuse of your code. Linking everything to a single "hard-coded" NSManagedObjectContext in the AppDelegate is fragile and reduces the flexibility of your code.

I discuss this in depth on The Mac Developer Network. (edit: lost link now via Wayback Machine's Cache)




回答2:


You can also create a main context object in your main Nib. And link the controllers with this object. Or create a singleton if you only use one MOC.



来源:https://stackoverflow.com/questions/3174610/passing-managedobjectcontext-along-to-view-controller-hierarchy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!