Search code examples
iosswiftnsfetchedresultscontrollernsfetchrequestcorestore

CoreStore refetch predicate NSFetchRequest issue


if I got it clear I need to refetch monitor when I search something:

I have this function to refetch with provided string

func search(searchText: String) {
        self.monitor.refetch(.where(format: "%K CONTAINS[cd] %@", #keyPath(ListEntityType.name), searchText),
                             OrderBy<ListEntityType>(.ascending("name")))
    }

but this code is not compilable, only this below:

func search(searchText: String) {
        self.monitor.refetch(Where<ListEntityType>("name", isEqualTo: searchText),
                             OrderBy<ListEntityType>(.ascending("name")))
    }

But here is only equal operation, but I need to search not just entire word but as well substring with format: "%K CONTAINS[cd] %@

From CoreStore this is how function refetch looks like:

 public func refetch(_ fetchClauses: [FetchClause]) {

        self.refetch { (fetchRequest) in

            fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) }
        }
    }

public protocol FetchClause {

    func applyToFetchRequest<T>(_ fetchRequest: NSFetchRequest<T>)
}

Solution

  • Just replace this:

    .where(format: "%K CONTAINS[cd] %@", #keyPath(ListEntityType.name), searchText)
    

    with

    Where<ListEntityType>("%K CONTAINS[cd] %@", #keyPath(ListEntityType.name), searchText)
    

    Another syntax sugar: You can get rid of the #keyPath references and use \ListEntityType.name instead