I’ve been working on importing XML into an iPad Core Data application. I have a working NSXMLParser implementation for my files, and have been able to import the simpler (ie attribute-only) elements into Core Data.
Some of the XML dated has nested elements with text, and I’m a bit stumped on how to get Core Data to play nicely in the callback-centric world of NSXML.
If I see a new XML element, I need to insert a new managed object into my context. If I do this in NSXML’s didStartElement:, I need to preserve a reference to it so that I can store my XML text element when didEndElement: is called.
Given that my XML elements are nested, I may have encountered several didStartElements: before I encounter a didEndElement:, so I need something more than a single object instance to preserve the managed object across callbacks. (Also, I think that insertNewObjectForEntityForName: is autoreleased, so I need to retain a copy of the managed object.)
I thought I might build an object stack out of NSMutableArray's addObject: and removeLastObject: methods, but I wonder if there’s something simpler, or I’ve missed some piece of the big picture here.
I’ve run unto a similar problem, and as you mentioned, ended up using stacks with
addObject:,lastObjectandremoveLastObject:. It parses reasonably quickly.In my specific case, I had a number of Core Data entities, both with instance variables and to-many relationships to their child elements. I used two stacks, one for the objects, and one for the elements. In my case the parent elements did not have data of their own, ex:
So I had one stack of the entities that contained other entities (
ParentandChildin my example), with another containing the keypaths corresponding to the data (Parent_Data1,Parent_Data2andChild_Data1). When I found the data inparser:foundCharactersI would set it on the topmost entity usingsetValue:forKeyPath:and pop that when I got toparser:didEndElement:.Hope that helps.