Question

My problem is pretty common and lame (for me), though I cannot find the solution.

I have a basic setup of Core Data. A Source object that act as a parent, and it has a to-many connection to Item.

Item object has now only an itemName property for simplicity.

I display these values in a tableView, as the Source objects being the sections and their child entities are the rows of the tableView.

All great when I want to fetch simply, cause than I just fetch for the Source object and display all their items.

Problem comes, when I want to filter these values by entering text into the search bar. I don't know what predicate I should use to get the wanted values, I only want to display those Items that itemName property contains the text entered into the search bar.

I tried the code below, but this doesn't help, it displays the right Source objects (cause one or more of their items contain the characters) but this will show all of their Item children objects, which I don't want. :)

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"items.@count != 0 AND items.itemName contains[c] %@", searchTerm];
NSSortDescriptor *dateSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"modificationDate" ascending:NO];
return [self fetchCoreDataForEntityName:@"source" withPredicate:predicate withSortDescriptor:dateSortDescriptor];

Any ideas? I think it's pretty easy to solve, but I don't know how. Thanks in advance. :)

Was it helpful?

Solution

Assuming that the relationship is one-to-many, I suggest your fetched results controller fetches not the Source, but the Item entity with the sectionNameKeyPath set to the relationship and attribute name for its Source, e.g. @"source.title". Now the predicate is simple:

[NSPredicate predicateWithFormat:@"itemName contain[c] %@", searchString];

(To follow the convention, I would suggest to rename your attribute name. item.itemName seems redundant.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top