Core Data: Fetch via specific property (join relationship)

旧时模样 提交于 2019-12-04 13:30:02

问题


I have an core data model as follows

The attributes property of Page is a set of DictionaryEntry, they are values for my Page objects, much like a standard NSDictionary (except all of the keys and values are strings)

I have a Page that has a DictionaryEntry with key="title" and value="Home". How would i form a fetch request to load that specific page?


回答1:


You should have a look at the predicate syntax for subqueries. You can not use the usual ANY keyword as this only allows you to match one column not two at the same time.

  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]];

The simpler predicate ANY attributes.key = "title" AND ANY attributes.value = "home" would not work as it also returns pages that have two dicts e.g. key='addr'/value='home' and key='title'/value='pete'.




回答2:


Assuming you start by knowing the "key" to the DictionaryEntry of "Title".

Why don't create an NSFetchRequest on the DictionaryEntry object using your known "key" when you create an NSPredicate.

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"DictionaryEntry" inManagedObjectContext:_context]];
[request setPredicate:[NSPredicate predicateWithFormat:@"key == %@", keyValue]];

Once you have your valid DictionaryEntry object, you can then use your CoreData crufted up "page" relationship to get your valid Page.



来源:https://stackoverflow.com/questions/3725936/core-data-fetch-via-specific-property-join-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!