【问题标题】:NSExpressionDescription for empty result sets空结果集的 NSExpressionDescription
【发布时间】:2023-04-08 11:05:01
【问题描述】:

使用 Core Data,我有一个获取请求,使用表达式获取某个属性的最小值。如果我在请求上设置了一个导致没有结果匹配的谓词,我会得到 EXC_BAD_ACCESS。这是有道理的,因为您不能将 nil 添加到 NSArray 以获得结果,但是最好的解决方法是什么?

我可以只使用排序顺序和 1 的获取限制,但在 NSExpressionDescription API 中似乎有点疏忽,如果在评估之前没有匹配的对象,则无法返回默认结果或返回空数组表达式。

或者我是否完全误诊了 EXC_BAD_ACCESS,并且 NSExpressionDescriptions 用于获取请求的 setPropertiesToFetch 应该已经在这种情况下表现得很好?

【问题讨论】:

  • 你能发布你的获取请求吗?

标签: ios core-data exc-bad-access nsfetchrequest


【解决方案1】:

今天遇到了类似的情况。将您的 NSFetchRequest resultType 设置为 NSDictionaryResultType。

- (NSDate *)maxDateForEvent:(Event *)event withContext:(NSManagedContext *)context
{

    NSExpression *modifiedDateExpression = [NSExpression expressionForKeyPath:@"modifiedDate"];
    NSExpression *maxExpression = [NSExpression expressionForFunction:@"max:"
                                                              arguments:[NSArray arrayWithObject:modifiedDateExpression]];

    NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
    [expressionDescription setName:@"maxDate"];
    [expressionDescription setExpression:maxExpression];
    [expressionDescription setExpressionResultType:NSDateAttributeType];

    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    fetch.entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:context];
    fetch.propertiesToFetch = [NSArray arrayWithObject:expressionDescription];
    fetch.resultType = NSDictionaryResultType;
    fetch.predicate = [NSPredicate predicateWithFormat:@"event == %@", event];
    NSError *error;
    NSArray *array = [context executeFetchRequest:fetch error:&error];
    if (!array || ![array count]) {
        return [NSDate distantPast];
    }

    NSDate *date = [[array lastObject] objectForKey:@"maxDate"];
    if (!date) {
        return [NSDate distantPast];
    }

    return date;
}

【讨论】:

    【解决方案2】:

    第二段中的解决方法是我必须使用的,所以这似乎只是 API 疏忽。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多