问题
I am using a MainWindow.xib file that has the following configuration:
MainWindow.xib
- UITabBarController
- UINavigationBarController
- UITableViewControllerAlpha
- UINavigationBarController
- UITableViewControllerBeta
- UINavigationBarController
- UITableViewControllerCharlie
- UINavigationBarController
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 inapplicationDidFinishLaunching:
- 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 ofinitWithCoder
.
If that doesn't work, you still have at least these options:
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.Write a method like
loadDataFromMOC:
on your controller, which both sets the MOC and fetches from it, and call it fromapplicationDidFinishLaunching:
.
来源:https://stackoverflow.com/questions/7192591/cant-access-managed-object-context-when-view-is-initializing