开发者

Can't access managed object context when view is initializing

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!


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:.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜