2011-08-31 88 views
3

使用核心數據,我有一個獲取請求來獲取使用表達式的某個屬性的最小值。如果我在請求中設置了一個謂詞,導致沒有匹配的結果,我得到EXC_BAD_ACCESS。這是有道理的,因爲你不能將結果添加到NSArray中,但是最好的解決方法是什麼?空結果集的NSExpressionDescription

我可以使用排序順序和1的提取限制,但它似乎有點在NSExpressionDescription API中的監督,沒有辦法返回默認結果或返回一個空數組,如果沒有對象之前匹配評估表達。

或者我完全錯誤地診斷EXC_BAD_ACCESS,並且在提取請求上setPropertiesToFetch中使用的NSExpressionDescriptions應該已經對這種情況有合理的表現?

+0

您可以發佈您的獲取請求嗎? –

回答

0

第二段中的解決方法是我不得不使用的,所以這似乎只是一個API監督。

4

今天進入類似的情況。將您的NSFetchRequest結果類型設置爲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; 
}