【问题标题】:executeFetchRequest return nil on empty core dataexecuteFetchRequest 在空核心数据上返回 nil
【发布时间】:2014-08-07 04:26:18
【问题描述】:

我在 Core Data 中遇到了一个奇怪的问题。基本上,我有一个空的核心数据,其中包含学生和教师等几个模型。我尝试执行以下代码:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
request.predicate = [NSPredicate predicateWithFormat:@"(username = %@) AND (password = %@)", username, password];

// Determines if there is a match for student
NSError *error;
NSArray *matches = [self.context executeFetchRequest:request error:&error];
if (error || !matches || [matches count] > 1) {
    NSLog(@"Error in retrieving login match for student");
}
else if ([matches count]) {
    student = [matches firstObject];
}

奇怪的是 matches 原来是 nil 并且错误消息被打印出来。 match 不应该是一个空数组,因为空的核心数据只是意味着上下文找不到满足这些条件的 NSManagedObject 吗?

【问题讨论】:

  • 你试过记录错误吗?您的 if 语句不区分匹配是 nil 还是发生错误。
  • 是的,我实际上在 if 条件检查 nil 之前做了一个 NSLog 语句,它返回 true。
  • 什么是零?错误或匹配?
  • 如果你的结果是匹配数组,如果有错误,它应该是 nil。所以,你需要记录错误,看看它是否给了你任何东西。
  • 当我记录错误时,它给了我(null)。

标签: ios core-data


【解决方案1】:

简短回答 = 是的,应该。

根据Apple doc

executeFetchRequest 的返回值 ... 满足请求指定条件的对象数组 从接收器和关联的持久存储中获取 与接收者的持久存储协调器。 如果发生错误返回零如果没有对象符合请求指定的条件, 返回一个空数组

因此,请检查您的 NSError

【讨论】:

  • 发帖后几秒我就知道了:我的NSManagedObjectContext也是nil
猜你喜欢
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 2010-11-26
  • 1970-01-01
相关资源
最近更新 更多