我正在尝试在后台线程中将数据保存在CoreData中,但是它崩溃或不起作用,不知道我在哪里做错了吗?
当我尝试使用主线程时,它可以正常工作,我试图在google上找到后台线程中的一些信息,但是找不到关于它的有用文章。
任何帮助表示赞赏。
谢谢
这是目标-c代码,我尝试过
-(void)insertNameAndSurnameInDataBase:(NSString *)name surname:(NSString *)surname numbers:(NSArray *)numbers labels:(NSArray *)labels{
NSManagedObjectContext *backgroundMOC = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[backgroundMOC performBlock:^{
NSError *error;
NameAndSurname *nameAndSurname = [NSEntityDescription insertNewObjectForEntityForName:@"NameAndSurname" inManagedObjectContext:backgroundMOC];
NSString *nSurname = [NSString stringWithFormat:@"%@ %@",name,surname];
nameAndSurname.nameSurname = nSurname;
if ([backgroundMOC save:&error]) {
}
else{
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"NameAndSurname"
inManagedObjectContext:backgroundMOC];
// predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"nameSurname =[c] %@", nSurname];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSArray *fetchedObjects = [backgroundMOC executeFetchRequest:fetchRequest error:&error];
if([fetchedObjects count] > 0){
[numbers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
id obj2 = [labels objectAtIndex:idx];
obj = [obj stringByReplacingOccurrencesOfString:@" " withString:@""];
ContactNumber *phoneNumber = [NSEntityDescription insertNewObjectForEntityForName:@"ContactNumber" inManagedObjectContext:backgroundMOC];
phoneNumber.number = obj;
phoneNumber.label = obj2;
phoneNumber.nameAndSurname = fetchedObjects[0];
NSError *error;
if ([backgroundMOC save:&error]) {
}
else{
}
}];
}
}];
}