Objective c 如何获取核心数据中的一对多关系?

Objective c 如何获取核心数据中的一对多关系?,objective-c,core-data,entity-relationship,Objective C,Core Data,Entity Relationship,假设数据实体是:Bookshop>Books 例如,如何获取属于特定书店且名称中包含“cloud”的所有书籍?下面的方法感觉很笨拙 Bookshop *bookshop = (Bookshop *) nsManagedObjectFromOwner; NSString *searchTerm = @"cloud"; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity

假设数据实体是:
Bookshop>Books

例如,如何获取属于特定书店且名称中包含“cloud”的所有书籍?下面的方法感觉很笨拙

Bookshop *bookshop = (Bookshop *) nsManagedObjectFromOwner;
NSString *searchTerm = @"cloud";

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

NSPredicate *predicate = [NSPredicate predicateWithFormat:
              @"ANY bookshop.Name == '%@' && Name contain[cd] '%@'", 
              bookshop.Name, searchTerm];
[fetchRequest setPredicate: predicate];

如果有两家书店的名字非常相似,我如何改进代码来处理?此外,还可能提高获取的性能,因为UITableView应该更新为book name中的用户类型

这可能是个人喜好的问题,但我喜欢定义和使用fetch请求模板。然后你可以这样做:

Bookshop *bookshop = (Bookshop *) nsManagedObjectFromOwner;
NSString *searchTerm = @"cloud";

NSDictionary *substitutionDictionary = [NSDictionary dictionaryWithObjectsAndKeys:bookshop.Name, @"BOOKSHOP_NAME", searchTerm, @"BOOK_NAME", nil];
// BOOKSHOP_NAME and BOOK_NAME are the name of the variables in your fetch request template

NSFetchRequest *fetchRequest = [model fetchRequestFromTemplateWithName:@"YourFetchRequestTemplateName" substitutionVariables:substitutionDictionary];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Books" 
                      inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
它不是更少的代码,而是更少的笨拙,因为所有的获取请求都在一个地方定义。或者我误解了你的问题


至于问题的第二部分,我自己实际上没有使用过,但NSFetchedResultsControllerDelegate提供了自动更新结果表所需的方法。请尝试
-控制器:didChangeObject:atIndexPath:forChangeType:newindexath:
。显然,这意味着使用NSFetchedResultsController。

这可能是个人喜好的问题,但我喜欢定义和使用fetch请求模板。然后你可以这样做:

Bookshop *bookshop = (Bookshop *) nsManagedObjectFromOwner;
NSString *searchTerm = @"cloud";

NSDictionary *substitutionDictionary = [NSDictionary dictionaryWithObjectsAndKeys:bookshop.Name, @"BOOKSHOP_NAME", searchTerm, @"BOOK_NAME", nil];
// BOOKSHOP_NAME and BOOK_NAME are the name of the variables in your fetch request template

NSFetchRequest *fetchRequest = [model fetchRequestFromTemplateWithName:@"YourFetchRequestTemplateName" substitutionVariables:substitutionDictionary];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Books" 
                      inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
它不是更少的代码,而是更少的笨拙,因为所有的获取请求都在一个地方定义。或者我误解了你的问题

至于问题的第二部分,我自己实际上没有使用过,但NSFetchedResultsControllerDelegate提供了自动更新结果表所需的方法。请尝试
-控制器:didChangeObject:atIndexPath:forChangeType:newindexath:
。显然,这意味着使用NSFetchedResultsController