我正在开发一个使用 Core Data 进行存储的 iOS 应用程序。在我的商店中,每个实体都是唯一的,我正在构建一个函数,用我传入的另一个实体替换一个现有实体。这是我传递的一个实体示例:
NSManagedObjectContext *context = [[MyDB sharedInstance] managedObjectContext];
User *user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context];
NSNumber *userNumber = 12345;
user.id = userNumber;
user.name = @"John Doe";
user.email = @"john@doe.net";
user.createdDate = [NSDate date];
[[MyDB sharedInstance] updateUser:user];
在我的核心数据存储中,我已经有一个相同的实体,除了电子邮件地址是“john@doe.com”。我现在的更新是这样的:
-(void)updateUser:(User *)user {
NSError *error;
NSManagedObjectContext *context = [[MyDB sharedInstance] managedObjectContext];
// Create fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
// Create predicate
NSPredicate *pred = [NSPredicate predicateWithFormat:@"id == %@", user.id];
[fetchRequest setPredicate:pred];
NSArray *results = [context executeFetchRequest:fetchRequest error:&error];
if (error) {
// handle fetch error
} else {
user = [[User alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
for (User *recordToDelete in results) {
[context deleteObject:recordToDelete];//record gets deleted here, which is fine
}
[context save:&error]; //this doesn't save the new entity that I passed in
if (error) {
// handle save error
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id=%@", 12345];
[fetchRequest setPredicate:pred];
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
for (User *testObject in items) {
NSLog(@"ID: %@, Name: %@, Email: %@, Created Date: %@", [testObject id], [testObject name], [testObject email], [testObject createdDate]);
}
}
问题是上述函数删除了存储中的现有记录,但是它无法添加替换它的新实体。我该如何纠正?