2015-04-15 82 views
0

我正在使用核心數據來獲取對象列表。這些對象有一個名爲'categories'的屬性。此類別屬性是一個的NSDictionary從JSON構建的,如:NSPredicate嵌套字典動態密鑰

@{@"A":@YES, @"B":@NO, @"C":@YES} 

我想所有的核心數據對象的類別是真實的給定類別的關鍵。 我想:

NSString *categoryKey = @"A"; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categories.%K == YES", categoryKey]]; 
// or 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.categories.%@ == YES", categoryKey]]; 
// or 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categories[%@] == YES", categoryKey]; 
// Throws exception : Unsupported function expression categories["A"] 
// or 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categories[%K] == YES", categoryKey]; 
// Throws exception : Unsupported function expression categories[A] 
// or 
NSString *categoryKeyPath = [NSString stringWithFormat:@"categories.%@", categoryKey]; 
NSPredicate *p = [NSPredicate predicateWithFormat:@"%K == YES", categoryKeyPath]]; 

但執行我取(當然我有一些物體與categories[@"A"] = YES)時,它總是返回空數組。 我認爲問題來自嵌套的字典鍵路徑,但我找不到用一個謂詞來實現這一點的方法。

編輯:

爲了明確核心數據讀取時,我會用

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) { 
    return [[evaluatedObject.categories objectForKey:categoryKey] boolValue]; 
}]; 

predicateWithBlock:不支持。

回答

1

如果我理解正確categories是你的實體,它包含JSON數據的字符串屬性和管理對象的解析此JSON,因此它可以被理解爲一個字典。

問題是在執行提取前未創建託管對象。那時,categories只是一個字符串,沒有關鍵路徑將能夠從中提取您想要的信息。您需要獲取所有對象,以便構建其字典,然後過濾該集合。對於大數據集,這可能很慢。

核心數據旨在通過顯式建模數據來使用;如果你在一個字符串中包含你自己的數據結構,Core Data不能幫你。更習慣的設計是將一個Categories實體與對象的實體進行多對多關係。這使得通過獲取類別A然後在關係之後找到類別A中的所有對象變得微不足道。

+0

沒有類別不是字符串,它已經是一個NSDictionary。 – ryancrunchi

+0

核心數據本身不能存儲NSDictionary對象,只能使用簡單的數據類型,如字符串和數字。我的印象是,你剛剛開始學習Core Data,如果你理解得更好,應該回到這個問題上來。 –

0

試試這個

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.categories LIKE \"%@\":true", categoryKey]]; 
+0

對不起,總是空數組檢索 – ryancrunchi

+0

作了更改,請檢查 – Saif