I have a brain class that I want to get Rest services and put the info into core data.(I have looked at RestKit object mapping, but don’t fully understand it yet and want to keep it simpler). I want to have the Core Data knowledge in my engine class, but to cover my bases, I add the ManagedObjectContext to all the VC’s in the Tab Bar Controller, like so (in app delegate):
UITabBarController *tabBar = (UITabBarController *)self.window.rootViewController;
NSArray *viewControllers = [tabBar viewControllers];
NSManagedObjectContext *context = self.managedObjectContext;
self.engine.managedObjectContext = context;
for (id viewController in viewControllers) {
[viewController setManagedObjectContext:context];
}
tabBar.selectedIndex = 2;
return YES;
However, I’m getting this error logged, when I try to check if coreData is available in my engine class:
if (self.managedObjectContext == NULL || [self.managedObjectContext isEqual:[NSNull null]]) {
NSLog(@"Error");
}
What am I doing wrong? How does one pass Core data to a non-viewController Class correctly?
EDIT: right before the IF Statement, this in the debugger:
(lldb) po self.managedObjectContext
(NSManagedObjectContext *) $1 = 0x00000000 <nil>
(lldb)
Assuming that the ‘context’ property on all the other view controllers is strong, then the answer is that when you go to assign it, its not yet been created. Try this:
Note that all users of context had better be on the same thread (I assume the main thread in our code).
That said, a better solution would be for the class that manages the contect to “vend” dictionaries or arrays to interested parties, and keep all your context access located in one file (or class). This will make future debugger a big easier (IMHO)>
EDIT: If the issue is that the value is set in the original code you posted – I assume this is your appDelegate, and the managedObjectContext is a strong property, then log the set operation:
Now, in each of your viewControllers, in viewDidLoad, add the line:
You will find one of these to be true:
1) you set the moc on three viewControllers just fine, but somewhere else you set a viewController and didn’t set the moc (some other code)
2) viewControllers is nil when you go to set the MOC on them (logic error)
3) The ViewControllers you set the MOC on and the ones that log the message I suggested are the same, but the MOC is nil when the VC prints the log message. In this case something in the VC is resetting MOC to nil – maybe in viewDidLoad.