如何获取核心数据中的一对多关系? [英] How to fetch one to many relationship in core data?
问题描述
让我们说数据实体是: Bookshop< --->>书
Let say the data entities are: Bookshop <--->> Books
如何获取属于某个书店的所有书,例如名称中包含cloud?以下方法感觉笨重。
How do I fetch all books belonging to a specific book shop that contain "cloud" in the name for example? The following method feel clunky.
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应该更新为用户类型的书名。
How could I improve this code to handle if there are 2 book shops with very similar names? And maybe also performance improvement for fetching as the UITableView should update as the user type in book name.
推荐答案
这可能是个人喜好的问题,但我喜欢定义和使用获取请求模板。然后你可以这样做:
This might be a matter of personal taste, but I like to define and use fetch request templates. Then you can do something like this:
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];
这不是少的代码,但是不太笨重,因为所有的获取请求一个地方。或者我误解了你的问题?
It isn't less code, but it is less clunky because all of your fetch requests are defined in one place. Or maybe I'm misunderstanding your question?
至于你的问题的第二部分,我没有实际使用这个自己,但NSFetchedResultsControllerDelegate提供了方法,您需要自动保持结果表更新。尝试 -controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:
。显然它意味着使用NSFetchedResultsController。
As far as the second part of your question is concerned, I haven't actually used this myself, but the NSFetchedResultsControllerDelegate provides the methods you need to automatically keep your table of results up-to-date. Try -controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:
. Obviously it implies using an NSFetchedResultsController.
这篇关于如何获取核心数据中的一对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!