2010-10-24 107 views
1

假設數據實體是:Bookshop <--->> Books如何獲取核心數據中的一對多關係?

如何獲取屬於特定書店的名稱中包含「雲」的所有書籍,例如?以下方法感覺笨重。

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應該更新爲書名中的用戶類型而提高了讀取性能。

回答

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。