2010-08-25 48 views
0

我有一個名爲「Card」的核心數據實體,它與另一個實體「CardInfo」具有「信息」關係。這是一對多的關係:每張卡可以有多個CardInfos,但每個CardInfo只有一張卡。如何創建一組實體,這些實體都與具有特定屬性的其他實體有關係?核心數據

CardInfo實體只有兩個字符串「cardKey」和「cardValue」。目標是允許任意輸入卡的數據。說,你想知道一張卡片是什麼顏色的。然後,您爲每個卡片添加了一個CardInfo,該卡片的cardKey爲「color」,cardValue爲「black」或「red」。

我的一般問題是:如果每張卡都有一個CardInfo,CardKey和CardValue具有特定的值,那麼獲得一組卡的最佳方式是什麼。例如:與CardInfo cardKey ='color'和cardValue ='red'有關係的所有卡片?理想情況下,我返回所有適當卡*對象的NSSet。

回答

2

末的循環來做到這一點。一個簡單的KVC電話會很好地清理它。

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
[fetchRequest setEntity:[NSEntityDescription entityForName:@"CardInfo" inManagedObjectContext:self.managedObjectContext]]; 
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"cardKey = %@ AND cardValue = %@", thisKey, thisValue]]; 

NSError *error = nil; 
NSArray *items = [[self managedObjectContext executeFetchRequest:fetchRequest error:&error]; 
[fetchRequest release], fetchRequest = nil; 
NSAssert1(error == nil, @"Error fetching objects: %@\n%@", [error localizedDescription], [error userInfo]); 

return [items valueForKeyPath:@"@distinctUnionOfObjects.card"]; 
+0

要備份實際需要一套: 回報[NSSet中setWithArray:項目valueForKeyPath:@ 「@ distinctUnionOfObjects.card」]]; 謝謝! – 2010-08-26 17:21:32

0

這是我想出來的答案,但這兩部分過程似乎對我來說效率低下。我想必須有一個更優雅的方式與鍵值或東西不需要

-(NSSet *)cardsWithCardKey:(NSString *)thisKey cardValue:(NSString *)thisValue { 

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"CardInfo" 
     inManagedObjectContext:self.managedObjectContext]; 

    [fetchRequest setEntity:entity]; 

    NSPredicate *predicate = [NSPredicate 
           predicateWithFormat:@"(cardKey=%@) AND (cardValue=%@)", 
           thisKey,thisValue]; 

    [fetchRequest setPredicate:predicate]; 

    NSError *error; 
    NSArray *items = [self.managedObjectContext 
     executeFetchRequest:fetchRequest error:&error]; 
    [fetchRequest release]; 

    NSMutableSet *cardSet = [NSMutableSet setWithCapacity:[items count]]; 
    for (int i = 0 ; i < [items count] ; i++) { 
     if ([[items objectAtIndex:i] card] != nil) { 
      [cardSet addObject:[[items objectAtIndex:i] card]]; 
     } 
    } 
    return [NSSet setWithSet:cardSet]; 
} 
相關問題