Skip to content

Instantly share code, notes, and snippets.

@xslim
Created June 11, 2011 17:19
Show Gist options
  • Save xslim/1020767 to your computer and use it in GitHub Desktop.
Save xslim/1020767 to your computer and use it in GitHub Desktop.
NSXMLParser + CoreData Sample
#import <Foundation/Foundation.h>
#import "Item.h" // Core Data MO
// Synchronous parser ! Will lock thread !
@interface ItemParser : NSObject <NSXMLParserDelegate>
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; // MOC for newly created MO
@property (nonatomic, retain) Item *currentItem;
@property (nonatomic, retain) NSMutableString *currentString;
- (id)initWithContext:(NSManagedObjectContext *)managedObjContext;
- (BOOL)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error;
// Used to delete existing items in DB
- (void)deleteExistingItems;
@end
#import "ItemParser.h"
@implementation ItemParser
@synthesize managedObjectContext, currentItem, currentString;
- (id)initWithContext:(NSManagedObjectContext *)moc
{
self = [super init];
if (self) {
self.managedObjectContext = moc;
[self deleteExistingItems];
}
return self;
}
- (void)dealloc
{
self.managedObjectContext = nil;
self.currentItem = nil;
self.currentString = nil;
[super dealloc];
}
- (NSEntityDescription *)entityDescription
{
return [NSEntityDescription entityForName:@"Item" inManagedObjectContext:self.managedObjectContext];
}
#pragma mark - Parser methods
- (void)deleteExistingItems
{
NSEntityDescription *entity = [self entityDescription];
NSFetchRequest *fr = [[NSFetchRequest alloc] init];
[fr setEntity:entity];
NSError *error = nil;
NSArray *results = [self.managedObjectContext executeFetchRequest:fr error:&error];
if (error) {
NSLog(@"Error removing items: %@", [error localizedDescription]);
}
for (NSManagedObject *object in results) {
[self.managedObjectContext deleteObject:object];
}
// Update the data model effectivly removing the objects we removed above.
if (![self.managedObjectContext save:&error]) {
// Handle the error.
NSLog(@"%@", [error domain]);
}
}
- (BOOL)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error
{
BOOL result = YES;
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
parser.delegate = self;
// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
parser.shouldProcessNamespaces = NO;
parser.shouldReportNamespacePrefixes = NO;
parser.shouldResolveExternalEntities = NO;
[parser parse];
NSError *parseError = [parser parserError];
if (parseError && error) {
*error = parseError;
result = NO;
}
[parser release];
return result;
}
#pragma mark - NSXMLParser delegates
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if (qName) {
elementName = qName;
}
if ([elementName isEqualToString:@"item"]) {
self.currentItem = (Item *)[NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:self.managedObjectContext];
// Set attributes
self.currentItem.attribute = [attributeDict objectForKey:@"attribute"];
} // else if.....
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if (qName) {
elementName = qName;
}
// If we're at the end of a additive. Save changes to object model
if ([elementName isEqualToString:@"item"]) {
NSError *error;
// Store what we imported already
if (![self.managedObjectContext save:&error]) {
NSLog(@"%@", [error domain]);
}
}
/*
else if ([elementName isEqualToString:@"title"]) {
NSString *string = [self.currentString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
self.item.title = string;
}
*/
self.currentString = [NSMutableString string];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[self.currentString appendString:string];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment