views:

391

answers:

1

Hi, I am trying to develop a test Core Data app so i can use it in my main app. But im having problems fetching stored data.

I have 1 Entity "User" with 2 attributes: name (String) & email (String) I can successfully populate my store file with data... here is the code im using below. Any help would be greatly appreciated.

NSManagedObjectContext *managedObjectContext;
NSError *error;

NSString *basePath = @"/Users/Jamie/Desktop";
NSURL *storePath = [NSURL fileURLWithPath: [basePath stringByAppendingPathComponent:@"datastore.xml"]];

NSLog(@"Data Store path: %@", storePath);

NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[NSManagedObjectModel mergedModelFromBundles:nil]];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:storePath options:nil error:&error]) {
 NSLog(@"Unable to load Core Data Store");
 NSLog(@"ERROR: %@", error);
 return 1;
} else {
 NSLog(@"Loaded Core Data Store");
}

managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:persistentStoreCoordinator];

// Add data to store.
/*
NSManagedObject *mo = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:managedObjectContext];
[mo setValue:@"jamie" forKey:@"name"];
[mo setValue:@"[email protected]" forKey:@"email"];
if([managedObjectContext save:&error]) {
    NSLog(@"Saved data to store");
} else {
    NSLog(@"Unable to save data to store");
    NSLog(@"ERROR: %@", error);
}
*/

// Fetch all the data - not worrying about using a predicate.
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"User" inManagedObjectContext:managedObjectContext];   
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];

NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
+1  A: 

Fixed - If you split out the parts into seperate methods it all works :)

Jamie