6

コア データのフィールドの最大値が必要なため、次のリクエストを設定しました。

// Create fetch
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:context]];
[fetch setResultType:NSDictionaryResultType];

// Expression for Max ID
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"myNumbericID"];
NSExpression *minExpression = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"maxID"];
[expressionDescription setExpression:minExpression]; 
[expressionDescription setExpressionResultType:NSDoubleAttributeType];
[fetch setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];

// Execute the fetch. 
double theID = 0;
NSError *error;
NSArray *objects = [context executeFetchRequest:fetch error:&error]; 
if (objects && [objects count] > 0) { 
    theID = [((NSNumber *)[[objects objectAtIndex:0] valueForKey:@"maxID"]) doubleValue];
}

ただし、事前にコンテキストに挿入された新しいオブジェクトは考慮されていないようです。これはどのように機能するはずですか?ストア内のオブジェクトでのみ機能しますか?

ドキュメントでそれへの参照が見つかりません。

ありがとう、

マイク

4

3 に答える 3

7

Apple Developer Forums から回答があり、保存されていない変更が考慮されていないことが確認されました。

于 2009-10-27T21:11:44.463 に答える
0

参考までに、NSExpression セクション全体をスキップしてフェッチを続行し、最大値にコレクション演算子を使用できます。

theID = [objects valueForKeyPath:"@max.myNumbericID"];
于 2011-01-10T22:41:50.007 に答える