2009-05-09 9 views
7

私はCore Dataを使いこなしています。私がやろうとしていることに似ているという例は見つからないので、私は何かが分からないと確信しています。関係を通じてコアデータクエリを実行する方法は?

私はDVDデータベースを使いこなしています。私は2つの実体を持っている。映画(タイトル、年、評価、俳優との関係)、俳優(名前、性別、写真)。

すべての映画を取得するのは簡単です。タイトルに「殺す」とのすべての作品を取得することは簡単です

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Winery" 
inManagedObjectContext:self.managedObjectContext]; 

、私はちょうどNSPredicateを追加します:それはちょうどだ

NSPredicate *predicate = [NSPredicate predicateWithFormat: 
@"name LIKE[c] "*\"Kill\"*""]; 

しかし、Core Dataは、管理のためのIDフィールドから抽象的に思えますオブジェクト...どのようにオブジェクト(または:関係に対するクエリ)である属性に対してクエリを実行するのですか?

つまり、すでにActorオブジェクトを持っていると仮定して、私は([Object id 1 - 'Chuck Norris']と関係しています)、 "Object id 1 - 'Chuck Norris'] "?

答えて

6

アクターとムービーエンティティの間に1対多の逆関係があると仮定すると、特定のエンティティと同じ方法でチャックノリスのエンティティを取得し、ムービーの配列にアクセスできますアクターエンティティ上の関係に付けられたエンティティ。

// Obviously you should do proper error checking here... but for this example 
// we'll assume that everything actually exists in the database and returns 
// exactly what we expect. 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Actor" inManagedObjectContext:self.managedObjectContext]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE[c] 'Chuck Norris'"]; 
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
[request setEntity:entity]; 
[request setPredicate:predicate]; 

// You need to have imported the interface for your actor entity somewhere 
// before here... 
NSError *error = nil; 
YourActorObject *chuck = (YourActorObject*) [[self.managedObjectContext executeFetchRequest:request error:&error] objectAtIndex:0]; 

// Now just get the set as defined on your actor entity... 
NSSet *moviesWithChuck = chuck.movies; 

この例では、プロパティを使用して10.5と仮定していますが、アクセサーメソッドを使用して10.4でも同じことができます。

5

それとも、別の述語を使用することができます

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Actor" inManagedObjectContext:self.managedObjectContext]; 

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",@"Chuck Norris"] 
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
[request setEntity:entity]; 
[request setPredicate:predicate]; 

YourActorObject *chuck = [[self.managedObjectContext executeFetchRequest:request error:nil] objectAtIndex:0]; 
[request release]; 

NSSet *moviesWithChuck = chuck.movies; 
関連する問題