My goal is
I want to store an array of data into coreData. Here is my array
let storageArr = ["Teja", "Teja two", "Teja Ri", "Bhanu", "Stack", "Stack over", "Stack over flow"] as NSObject
And if user is typing in the Textfield I need to show them(related to that character) in drop down (tableView).
Let's say user typed "Te". I need to show Teja, Teja two, Teja Ri in table view.
I have done everything. But am unable to fetch only Teja, Teja two, Teja Ri from array.
Here is the code which I tried
override func viewDidLoad() {
super.viewDidLoad()
savingDataToLocalDB()
}
@IBAction func searchBtnClicked(_ sender: Any) {
setUpData(searchKeyword: searchTF.text)
}
func savingDataToLocalDB(){
let saveContext = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
let data: SearchList = NSEntityDescription.insertNewObject(forEntityName: "SearchList",
into: saveContext!) as! SearchList
data.names = storageArr
do {
try saveContext?.save()
print("data saved")
} catch {
print(error)
}
}
func setUpData(searchKeyword: String){
let fetchContext = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
let fetchReq = NSFetchRequest<NSManagedObject>(entityName: "SearchList")
do {
let data = try fetchContext?.fetch(fetchReq)
var filteredData = data as! [SearchList]
print(filteredData[0].names) // Am getting data here
//following line is not working
let wasfilteredData = filteredData.filter { $0.names!.lowercased().contains(searchKeyword.lowercased()) } as NSArray
} catch {
print(error)
}
}
Here in viewDidLoad()
am calling savingDataToLocalDB()
which means storing in coreData
And in @IBAction
am fetching data from coreData.
But in setUpData(searchKeyword: String)
method am unable to filer data consists of "Te"(user entered in textfiled)
Please find the following image. That's how I created entity
Where I am doing wrong?
It appears that you have a SINGLE entity in your database, with a transformable property of 'names'. That property is a transformable Array. Which means that it is stored in the database as Data and is encoded and decoded automatically. The database cannot search or sort this array because 1) it is a single property, not collection of entities and 2) it is stored as data. So all management must be done in memory, which means you have none of the benefits of core-data while having all of the cost.
Next, in your code you fetch ALL of the
SearchList
. Your database contains one so you get back and array of length 1. You then filter that Array of SearchList - NOT the array of names, and you get back the same searchList Array that you started with because that SearchList indeed passes the test.Perhaps you want:
Or perhaps you should consider having each entity contain only term, and then you search using predicates.