iOS:CoreData更新数据时发生异常 [英] iOS: CoreData Exception when updating data

查看:106
本文介绍了iOS:CoreData更新数据时发生异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用CoreData更新数据库中的现有记录,但是当使用Managed Object访问器方法时,我会收到异常。

I am trying to update an existing record in a database using CoreData, but I am getting an exception when using the Managed Object accessor method.

代码摘录:

NSManagedObjectContext *tmpManagedObjectContext = [self.fetchedResultsController managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:tmpManagedObjectContext];
[request setEntity:entity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"contact_id = %@", [dict objectForKey:@"contact_id"]];
[request setPredicate:predicate];

NSError *error = nil;
[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:[NSArray arrayWithObjects:@"first_name",@"sync_status",nil]];

Contact *contact = [[managedObjectContext executeFetchRequest:request error:&error] objectAtIndex:0];
contact.sync_status = @"Y";

error = nil;
if (![tmpManagedObjectContext save:&error]) {
    NSLog(@"Error setting sync status on contact record - error: %@", [error localizedDescription]);
}

导致错误的行是:

contact.sync_status = @"Y";

错误 *由于未捕获异常而终止应用程序'NSInvalidArgumentException',reason:' - NSKnownKeysDictionary1 setSync_status:]:无法识别的选择器发送到实例0x8907fd0'
*
第一次调用堆栈:

Contact是一个NSManagedObject类,在Xcode中。

Contact is a NSManagedObject class which I automatically generated in Xcode.

我的做法不正确吗?我在检索或删除记录时没有遇到任何问题,但我不知道如何更新数据。

Is my approach incorrect here? I haven't had any problems with retrieving or deleting records, but I am stumbling on how to update data.

任何指导或帮助将非常感谢。感谢。

Any guidance or help would be greatly appreciated. Thanks.

推荐答案

您已将抓取请求配置为返回字典,而不是托管对象。如果要更新返回的对象,则必须在获取请求中请求这些对象 - 即,使用默认行为,而不是您正在执行的操作。

You've configured your fetch request to return dictionaries instead of managed objects. If you want to update the returned objects, you must ask for them in the fetch request - that is, use the default behaviour instead of what you are doing.

删除这些行:

[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:[NSArray arrayWithObjects:@"first_name",@"sync_status",nil]];

你会很好。如果你只想在fetch中返回某些属性,而是想要整个对象,则使用上面的行。

And you'll be fine. The lines above are used if you only want to return certain properties in the fetch, but you want the whole object.

这篇关于iOS:CoreData更新数据时发生异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆