我有一个核心数据模型如下
的attributes
属性Page
是一组DictionaryEntry
,它们是我的 Page 对象的值,很像标准NSDictionary
(除了所有keys
和values
都是字符串)
我有Page
一个DictionaryEntry
withkey="title"
和value="Home"
。我将如何形成一个获取请求来加载该特定页面?
我有一个核心数据模型如下
的attributes
属性Page
是一组DictionaryEntry
,它们是我的 Page 对象的值,很像标准NSDictionary
(除了所有keys
和values
都是字符串)
我有Page
一个DictionaryEntry
withkey="title"
和value="Home"
。我将如何形成一个获取请求来加载该特定页面?
您应该查看子查询的谓词语法。您不能使用通常的 ANY 关键字,因为这只允许您同时匹配一列而不是两列。
NSString *keyValue = @"title";
NSString *valueValue = @"home";
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Page" inManagedObjectContext:_context]];
[request setPredicate:[NSPredicate predicateWithFormat:@"(SUBQUERY(attributes, $a, $a.key == %@ && $a.value == %@).@count != 0)", keyValue, valueValue]];
更简单的谓词ANY attributes.key = "title" AND ANY attributes.value = "home"
不起作用,因为它还返回具有两个字典的页面,例如 key='addr'/value='home' 和 key='title'/value='pete'。
假设您首先知道“标题”的 DictionaryEntry 的“键”。
在创建 NSPredicate 时,为什么不使用已知的“密钥”在 DictionaryEntry 对象上创建 NSFetchRequest。
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"DictionaryEntry" inManagedObjectContext:_context]];
[request setPredicate:[NSPredicate predicateWithFormat:@"key == %@", keyValue]];
一旦你有了有效的 DictionaryEntry 对象,你就可以使用 CoreData 修饰的“页面”关系来获取有效的页面。