尝试将记录添加到数据库时出现以下错误:
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)我尝试了所有我能添加的方法,但我目前使用的是这个类别:
#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我可以在第一次创建数据库时将数据添加到数据库中(如果我从设备上删除了应用程序),如下所示:
- (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);
}但在那之后,我一直收到同样的错误。有什么想法吗?
发布于 2012-02-13 16:51:00
#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]<=0) {
//create a new one
patient = [NSEntityDescription insertNewObjectForEntityForName:@"Patient" inManagedObjectContext:context];
patient.lastName = lastName;
[context performSelectorOnMainThread:@selector(save:) withObject:nil waitUntilDone:YES];
} else {
patient = [patients lastObject];
}
return patient;
}
@end只需将新创建的对象保存在主线程上。因此,您在辅助线程(GCD)上创建对象,这些更改只有在您将上下文保存在主线程上后才会生效
[context performSelectorOnMainThread:@selector(save:) withObject:nil waitUntilDone:YES]; https://stackoverflow.com/questions/9254521
复制相似问题