我看到很多关于核心数据更新的问题。实际上我正在创建一个简单的应用程序联系人列表应用它包含添加,编辑,删除和更新功能。这是我的更新代码。它可以工作和更新,但它会更新所有联系人列表。我只需要更新特定的联系人。
- (IBAction)updatePressed:(id)sender
{
delegate = [[AppDelegate alloc]init];
delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
name2 = emailtxt1.text;
email2 = nametext1.text;
mobile2 = numbertxt1.text;
dict = [[NSMutableDictionary alloc] init];
[dict setObject:nametext1.text forKey:@"NAME"];
[dict setObject:emailtxt1.text forKey:@"EMAIL"];
[dict setObject:numbertxt1.text forKey:@"MOBILE"];
[delegate UpdateDiary:dict];
}
- (void)UpdateDiary:(NSMutableDictionary *)dictionary
{
NSLog(@"update book Details Function Entered");
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Diary"inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSArray *mutableFetchResult = [[[self.managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy] autorelease];
if (mutableFetchResult == nil) {
NSLog(@"Fetch result error %@, %@", error, [error userInfo]);
}
for (Diary *ob2 in mutableFetchResult)
{
{
ob2.name = [dictionary objectForKey:@"NAME"];
ob2.email=[dictionary objectForKey:@"EMAIL"];
ob2.phone=[dictionary objectForKey:@"MOBILE"];
}
}
if(![self.managedObjectContext save:&error])
{
if([error localizedDescription] != nil)
{
NSLog(@"%@",error);
}
else
{
}
}
}
答案 0 :(得分:1)
您需要在获取请求中设置谓词。这就是它如何知道你想要的对象,而不仅仅是获取所有对象。
您可以执行以下操作:
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"email == %@", anEmailAddress];
如果你这样做了,那么执行获取请求的结果就是与你在谓词中设置的电子邮件地址相匹配的对象。
当然,请注意,如果有多个具有相同电子邮件地址的对象,则获取请求将获取所有这些对象。
当您进入编辑表单时,更好的应用程序设计可能会保留您正在编辑的Core Data对象,可能位于视图控制器的属性中。 (我认为你会知道,因为你需要知道填充字段的内容。)这样你就不需要在用户尝试提交编辑时执行提取了 - 你可以使用你周围的物体。
答案 1 :(得分:0)
- (void)UpdateBook:(NSMutableDictionary *)dictionary
{
NSLog(@"update book Details Function Entered");
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Book"inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"bookID = %@", [dictionary objectForKey:@"vID"]];
NSArray *mutableFetchResult = [[[self.managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy] autorelease];
if (mutableFetchResult == nil) {
NSLog(@"Fetch result error %@, %@", error, [error userInfo]);
}
for (Book *ob2 in mutableFetchResult)
{
{
ob2.name = [dictionary objectForKey:@"VName1"];
ob2.author=[dictionary objectForKey:@"VAuthor1"];
ob2.discription=[dictionary objectForKey:@"VDiscription1"];
ob2.bookID=[dictionary objectForKey:@"vID"];
}
}
if(![self.managedObjectContext save:&error])
{
if([error localizedDescription] != nil)
{
NSLog(@"%@",error);
}
else
{
}
}
}