开发者

How do I give my parsing code access to my ManagedObjectContext?

I'm writing an iPhone app which fetches an XML file, parses it and then saves the parsed objects to Core Data. I've got everything working up to the point where I save the objects to Core Data. I imagine it's got something to do with how I'm referencing the ManagedObjectContext but I can't figure out where I'm going wrong. I've looked 开发者_如何学Goat the SO question here but I'm still stumped. I've followed the Core Data Tutorial for iPhone and got that working, but seem to have hit a problem applying what I've learned to my own project. My app is different in structure to the example in the tutorial.

My app is a UITabBar with three subviews, let's call them A, B and C and a separate class file which is just used for fetching the XML called XMLParser. This XML fetching class is called on the press of a button in ViewController 'C'.

When I parse the XML, I try to save the parsed objects on-the-fly to Core Data. It fails on the first attempt with the following error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason:
'+entityForName: could not locate an NSManagedObjectModel for entity name 'Branch'' 

In my app delegate, I have the following code relating to my xmlparser class:

At the top of the AppDelegate.m file

#import "XMLParser.h"

Inside applicationDidFinishLaunching

NSManagedObjectContext *context = [self managedObjectContext];
XMLParser *xmlparser = [[XMLParser alloc] init];
xmlparser.managedObjectContext = context;
[xmlparser release];

Instead of pasting massive chunks of code into the question right now, if someone can see anything up with what I've written so far then please ask for more code or a better explanation.

Edit: I've checked everything in the accepted answer for this SO question and I have all this configured

Thanks


EDIT

I realise now that because I actually instantiate an XMLParser object upon the press of a button in ViewController C, the managedObjectContext set in applicationDidFinishLaunching does not apply to the newly instantiated object. So, how do I give the XMLParser access to my applications ManagedObjectContext when I instantiate it after pressing the button on my ViewController?


You are creating an XMLParser object and setting its managed object context. This is fine.

However, then you release it. If you plan to use the object, you should not release it immediately.

UPDATE
You can pass the managed object context into your view controller(s) in applicationDidFinishLaunching:. You can also get it from the app delegate or another singleton that manages your Core Data stack.

You can get the managed object context from the app delegate like this:

[UIApplication sharedApplication].delegate.managedObjectContext
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜