iosswiftcore-datasearchbar

How to search on a search bar on the basis of Core-Data entity and attribute


By firing an API, I am getting a certain list of titles which I am storing in an array like so:

self.arr1.updateValue(user, forKey: "title") and
self.sampleArray.append(self.arr1["title"] as! String)

Now sampleArray has all the titles I need and I need to filter on the basis of these titles. My coredata model has an entity called Posts and attributes content,title.

Also, currently this is how I am filtering:

    filtered = sampleArray.filter({ (text) -> Bool in
                let tmp: NSString = text as NSString
                let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
                return range.location != NSNotFound
            })

Here, sampleArray has just a list of names and those names are added to the array named 'filtered', but the issue is that on clicking a row we go to a webview using segue and that webview has some content in a paragraph. Clicking on each of the row shows the webview with a different data. With this filtering that I am doing above, when I click on the row I get after filtering, the webview data shown is incorrect. In other words, I am not able to figure out how I will pass the correct array so that the correct webview content is shown.

My entity 'Posts' has the attributes 'title' and 'content'. If I can filter the Posts and then get the title from it, then I think I can get the content also, but I am not able to figure out how that is done.


Solution

  • You are searching on the basis of just the attributes while you are to search on the basis of your managed object array. Try this format...

    filtered = self.arrayOfYourManagedObjectType.filter { ($0.title?.lowercased().contains(searchText.lowercased()))! }