我正在尝试更新Core Data中的一些记录。我采取了以下步骤来完成它
我遇到了两个问题
我的代码:
- (void)fetchExpenses {
// Define our table/entity to use
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Expense" inManagedObjectContext:managedObjectContext];
// Setup the fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
// Define how we will sort the records
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"publishTimestamp == nil"];
[request setPredicate:predicate];
// Fetch the records and handle an error
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (!mutableFetchResults) {
// Handle the error.
// This is a serious error and should advise the user to restart the application
}
// Save our fetched data to an array
[self setExpenseArray: mutableFetchResults];
[mutableFetchResults release];
[request release];
}
- (void) save: {
[self fetchExpenses];
int i = 1;
int max = [expenseArray count];
for(i=1; i<=max; i++) {
// Get the expense selected.
Expense *expense = [expenseArray objectAtIndex: i];
// Do your updates here
[expense setTimestamp:2]
}
}
答案 0 :(得分:2)
您在日志中看到的fault
并不表示错误,但意味着托管对象未完全加载到内存中,而是represented by a fault object。这是正常行为。当您尝试访问或更改对象属性时,完整对象将“出现故障”或读入内存。这是一个令人困惑的旧时尚数据库术语,可以追溯到20世纪60年代。
您的代码不会保存任何对象。在托管对象上下文上调用save
之前,不会保留对内存中托管对象的更改。
您也不想使用这样的可变副本:
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
...因为它会浪费内存并导致重复的托管对象。 Apple文档中有一些代码启动但是错误。相反,只需使用:
NSArray *fetchResults=[managedObjectContext executeFetchRequest:request error:&error];
...将返回与fetch匹配的自动释放的托管对象数组。