Can't access managed object context when view is initializing

五迷三道 提交于 2019-12-11 16:17:41

问题


I am using a MainWindow.xib file that has the following configuration:

MainWindow.xib

  • UITabBarController
    • UINavigationBarController
      • UITableViewControllerAlpha
    • UINavigationBarController
      • UITableViewControllerBeta
    • UINavigationBarController
      • UITableViewControllerCharlie

But based on the following post: Why does Core Data initialization fail when I attempt to do it at these points? and the breakpoints that I've placed, I've come to the conclusion that initWithCoder is being used to init all of the UITableViewControllers and that there is no way to reliably use the managedObjectContext at that point in the applicaiton lifecycle.

So does this mean that I have to throw out all the "easy" design work and layout that I've performed in MainWindow.xib and do it programatically? Does using core data, really mean not being able to use NIB files? Or is there some middle-ground?

Please let me know, Thanks!


回答1:


There's no problem using Core Data, table views, and NIBs together. I presume you need to fetch some objects from the MOC for your table view, and you're having problems finding the MOC when you need to do that.

This approach works for me:

  • Define nib as target's main interface.
  • Load nav controller and root view controller in nib.
  • Set root view controller's managedObjectContext property in applicationDidFinishLaunching:
  • Fetch from MOC in root view controller's viewDidLoad

So, try this first:

  • Have the app delegate set the controller's managedObjectContext in applicationDidFinishLaunching:
  • Do the fetch in viewDidLoad instead of initWithCoder.

If that doesn't work, you still have at least these options:

  1. Set the controller's managedObjectContext in applicationDidFinishLaunching:, but don't fetch data until your data source methods are called. In those methods, conditionally complete the fetch if it hasn't already been done.

  2. Write a method like loadDataFromMOC: on your controller, which both sets the MOC and fetches from it, and call it from applicationDidFinishLaunching:.



来源:https://stackoverflow.com/questions/7192591/cant-access-managed-object-context-when-view-is-initializing

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