我希望它与其他链接重复,例如:How to update existing object in Core Data?
但我的情况有点不同。
事情是我创建了一个示例核心数据项目。
第1步:我有3个ViewController类
在第一个屏幕中:我在核心数据中创建了一个字段"密码" ==>我使用以下代码保存:
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new userInfo
NSManagedObject *newuserInfo = [NSEntityDescription insertNewObjectForEntityForName:@"UserInfo" inManagedObjectContext:context];
[newuserInfo setValue:self.passwordTxtFldRef.text forKey:@"password"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
// NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
在第二屏幕中:我有两个文本字段:Oldpassword
& newpassword
。这里我在NSUserDefaults中保存了旧密码,在第二个屏幕中,我检查了oldpassword
是否正确的条件天气 - >它很完美。
我的要求是,我要将Oldpassword
更新为newpassword
--->在第二个屏幕本身。
我该怎么做?你可以帮我解决这个问题吗?
答案 0 :(得分:0)
这里我使用的代码如下:
-(void)getSavedDataFromCoreData{
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"UserInfo" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"password like %@",oldPasswordStr];
[request setPredicate:predicate];
NSError *error;
NSArray *matchingData = [context executeFetchRequest:request error:&error];
if(matchingData.count<=0){
//NSLog(@"Cancel");
}else{
for(NSManagedObject *obj in matchingData){
[obj setValue:alertTextField2.text forKey:@"password"];
}
[context save:&error];
NSMutableArray *array3 = [matchingData valueForKey:@"password"];
NSString *value3 = [array3 objectAtIndex:0];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:value3 forKey:@"savedPassword"];
[defaults synchronize];
[self showGeneralAlertMessage:@"Password Changed Successfully" withTitle:@"Success"];
}
}
答案 1 :(得分:0)
这将帮助您更新值。
- (无效)updateDataInCoreData {
NSManagedObjectContext *context = appDelegate.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"number == %@",userDict[@"number"]];
[fetchRequest setPredicate:predicate];
[fetchRequest setFetchLimit:1];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *arrResult = [context executeFetchRequest:fetchRequest error:&error];
User *entity1 = arrResult[0];
entity1.number = @"123456";
[appDelegate saveContext];
}