NSFetchRequest
オブジェクトのプロパティをで返すがありますNSDictionaryResultType
。このディクショナリ内でオブジェクトのObjectIdを取得することもできますか?NSManagedObjectResultType
それ以外の場合は、返されるアイテムの数が多い場合に返されるタイプがはるかに遅いクエリを実行する必要があります。
5 に答える
はい、できます。非常に気の利いた、しかし十分に文書化されていないNSExpressionDescription
クラスを使用します。に設定したオブジェクトNSExpressionDescription
の配列に、適切に構成されたオブジェクトを追加する必要があります。NSPropertyDescription
setPropertiesToFetch:
NSFetchRequest
例えば:
NSExpressionDescription* objectIdDesc = [[NSExpressionDescription new] autorelease];
objectIdDesc.name = @"objectID";
objectIdDesc.expression = [NSExpression expressionForEvaluatedObject];
objectIdDesc.expressionResultType = NSObjectIDAttributeType;
myFetchRequest.propertiesToFetch = [NSArray arrayWithObjects:objectIdDesc, anotherPropertyDesc, yetAnotherPropertyDesc, nil];
NSArray* fetchResults = [myContext executeFetchRequest:myFetchRequest error:&fetchError];
次に@"objectID"
、フェッチ要求から返される辞書にキーが必要です。
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"yourEntity" inManagedObjectContext:context];
request.sortDescriptors = [NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES], nil];
request.predicate = nil;
request.fetchLimit = 20;
NSError *error = nil;
NSArray fetchedResults = [context executeFetchRequest:request error:&error];
NSLog(@"%@", [fetchedResults valueForKey:@"objectID"]);
フェッチされた結果はすでに配列に含まれているので、valueForKey:@ "objectID"を使用してそれらを引き出してみませんか?クリーンでシンプルな場合、必要なフェッチリクエストは1つだけなので、必要な他のすべてのデータもプルできます。
SwiftでのNickHutchinsonの回答:
let idDescription = NSExpressionDescription()
idDescription.name = "objectID"
idDescription.expression = NSExpression.expressionForEvaluatedObject()
idDescription.expressionResultType = .objectIDAttributeType
担当者が足りないのでコメントできません:(
受け入れられた回答の迅速なバージョン
let objectIDExpression = NSExpressionDescription()
objectIDExpression.name = "objectID"
objectIDExpression.expression = NSExpression.expressionForEvaluatedObject()
objectIDExpression.expressionResultType = .objectIDAttributeType
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)
fetchRequest.resultType = .dictionaryResultType
//
var propertiesToFetch: [Any] = [objectIDExpression]
propertiesToFetch.append(contentsOf: entity.properties)
fetchRequest.propertiesToFetch = propertiesToFetch
私がこれまでに見つけた唯一の解決策は、次の違いを除いて、最初のフェッチ要求と同様の2番目のフェッチ要求を実行することです。
[fetchRequest setReturnsObjectsAsFaults:YES];
[fetchRequest setPropertiesToFetch:nil];
[fetchRequest setFetchLimit:1];
[fetchRequest setFetchOffset:index]; // The index for which the objectID is needed
[request setResultType:NSManagedObjectIDResultType];
これにより、フェッチリクエストは、必要なobjectIDという1つのオブジェクトのみを含む配列を返します。最初のフェッチリクエストの結果に10000個のオブジェクトが含まれている場合でも、パフォーマンスは良好のようです。
これを処理するためのより良い方法があれば、誰かがここに投稿していただければ幸いです。