【问题标题】:How to fetch one to many relationship in core data?如何获取核心数据中的一对多关系?
【发布时间】:2011-04-29 22:16:48
【问题描述】:

假设数据实体是: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];

如果有 2 家名称非常相似的书店,我该如何改进此代码以进行处理?并且也许还可以提高获取的性能,因为 UITableView 应该随着用户输入书名而更新。

【问题讨论】:

    标签: objective-c core-data entity-relationship


    【解决方案1】:

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

    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 提供了自动更新结果表所需的方法。试试-controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:。显然这意味着使用 NSFetchedResultsController。

    【讨论】:

      猜你喜欢
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多