我正在使用核心數據來獲取對象列表。這些對象有一個名爲'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:
不支持。
沒有類別不是字符串,它已經是一個NSDictionary。 – ryancrunchi
核心數據本身不能存儲NSDictionary對象,只能使用簡單的數據類型,如字符串和數字。我的印象是,你剛剛開始學習Core Data,如果你理解得更好,應該回到這個問題上來。 –