2012-02-09 87 views
1

這是我第一次嘗試使用CoreData,並且在從表中獲取最大日期時遇到了一些麻煩。使用CoreData獲取最大值

這基本上就是我想要做的事:

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Radar" inManagedObjectContext:managedObjectContext]; 
[request setEntity:entity]; 

NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"modifiedOn"]; 
NSExpression *maxDate = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:keyPathExpression]]; 

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

[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]]; 

NSError *error = nil; 
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error]; 
if (objects == nil) { 
    // Handle the error. 
} 
else { 
    if ([objects count] > 0) { 
     NSLog(@"%d", [objects count]); 
     NSLog(@"MAx date: %@", [[objects objectAtIndex:0] valueForKey:@"modifiedOn"]); 
    } 
} 

這個代碼在某種程度上確實的我想的正好相反,打印最小日期。由於我剛剛開始使用CoreData,很明顯我出錯了,但是什麼?

+0

查看第二個答案在這裏:http://stackoverflow.com/questions/4789033/querying-max-min-and-other-via-core-data – sho 2012-02-09 23:43:23

+0

@sho - 我得到它的工作使用你指出我的答案,然而,官方文件使用我粘貼在問題上的代碼。任何想法爲什麼這個代碼幾乎是來自文檔的代碼的副本不工作?謝謝 – Raphael 2012-02-10 01:05:05

回答

0

也許你應該嘗試NSLog [對象lastObject],而不是第一個?