I get this error when trying to add a record to my database:
2012-02-12 20:15:18.187 Flavma[3197:707] CoreData: error: Serious application error.
An exception was caught from the delegate of NSFetchedResultsController during a call to -
controllerDidChangeContent:. *** -[__NSArrayI objectAtIndex:]:
index 1 beyond bounds [0 .. 0] with userInfo (null)
I tried adding every way I can, but what I’m currently using is this category:
#import "Patient+Create.h"
@implementation Patient (Create)
+ (Patient *)patientWithLastName:(NSString *)lastName inManagedObjectContext:(NSManagedObjectContext *)context
{
Patient *patient = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Patient"];
request.predicate = [NSPredicate predicateWithFormat:@"lastName = %@", lastName];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *patients = [context executeFetchRequest:request error:&error];
if (!patients || ([patients count] > 1)) {
//handle error
} else if (![patients count]) {
//create a new one
patient = [NSEntityDescription insertNewObjectForEntityForName:@"Patient" inManagedObjectContext:context];
patient.lastName = lastName;
} else {
patient = [patients lastObject];
}
return patient;
}
@end
I am able to add data to my database when it’s first created (if I delete the app from my device), like so:
- (void) fetchPatientDataIntoDocument:(UIManagedDocument *)document
{
dispatch_queue_t fetchQ = dispatch_queue_create("Patient fetcher", NULL);
dispatch_async(fetchQ, ^{
[document.managedObjectContext performBlock:^{
[Patient patientWithLastName:@"Johnson" inManagedObjectContext:self.patientDatabase.managedObjectContext];
}];
});
dispatch_release(fetchQ);
}
But after that, I keep getting the same error. Any ideas?
Just save the newly created object on main thread.
Reason for this, you are creating the object on a secondary thread(GCD), those changes will not effect until you save the context on main thread