首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更新核心数据记录<fault>

更新核心数据记录<fault>
EN

Stack Overflow用户
提问于 2011-09-07 04:30:02
回答 1查看 2.2K关注 0票数 0

我正在尝试更新核心数据中的一些记录。我正在采取以下步骤来完成它

  1. 带有谓词的Fetch函数从核心数据中检索记录
  2. 将结果集存储在对象数组中
  3. 循环遍历数组并更新每个记录
  4. 调用保存上下文

我遇到了两个问题

  • 在初始运行之后,我在日志中得到了<故障>
  • 我不确定保存上下文是否真的会保存对象。

我的代码:

代码语言:javascript
复制
- (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]

  }
}
EN

回答 1

Stack Overflow用户

发布于 2011-09-07 13:48:53

您在日志中看到的fault并不表示错误,而是表示托管对象没有完全加载到内存中,而是由故障对象表示的。这是正常的行为。当您尝试访问或更改对象属性时,整个对象将被“故障”或读取到内存中。这是一个令人困惑的旧的数据库术语,可以追溯到20世纪60年代。

您的代码不保存任何对象。在调用托管对象上下文上的save之前,内存中托管对象的更改不会持久。

您也不希望使用这样的可变副本:

代码语言:javascript
复制
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];

…因为它浪费内存,并可能导致复制托管对象。苹果文档中有一些代码启动了这一过程,但它是错误的。相反,只需使用:

代码语言:javascript
复制
NSArray *fetchResults=[managedObjectContext executeFetchRequest:request error:&error];

…它将返回与获取匹配的托管对象的自动释放数组。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7328872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档