Andrew
Andrew

Reputation: 402

iOS How to optimized querys for data base Parse swift 4

I have one issues, if in shorter i have search module which connected to parse server.

And in this Data base i have more then 50 data table in which i store some data, and for searching i use this code:

 func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
    searchResult.removeAll(keepingCapacity: false)
    answer.removeAll(keepingCapacity: false)
    tableView.reloadData()

    let firstQuery = PFQuery(className: "table1")
    firstQuery.whereKey("question", contains: searchBar.text)

    let seccondQuery = PFQuery(className: "table2")
    seccondQuery.whereKey("question", contains: searchBar.text)

    let query3 = PFQuery(className: "table3")
    query3.whereKey("question", contains: searchBar.text)

    let query4 = PFQuery(className: "table4")
    query4.whereKey("question", contains: searchBar.text)

    let queryArry = [firstQuery, seccondQuery, query3, query4]
    for query in queryArry {
        query.findObjectsInBackground { (result, error) in
            if let objects = result {
                for object in objects {
                    let question = object.object(forKey: "question") as! String
                    let answer = object.object(forKey: "answer1") as! String
                    self.answer.append(answer)
                    self.searchResult.append(question)

                }

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                    self.resignFirstResponder()
                }
            }
        }

    }


}

As you can see i have 4 query, and some how i want to improve this because each time i don't want to copy this part of code:

let firstQuery = PFQuery(className: "table1")
firstQuery.whereKey("question", contains: searchBar.text)

Maybe some hove it's have possibility to improve?

Upvotes: 0

Views: 46

Answers (1)

Julien Kode
Julien Kode

Reputation: 5479

If you don't want to copy this part of code

let firstQuery = PFQuery(className: "table1")
firstQuery.whereKey("question", contains: searchBar.text)

You can may be do something like:

let query1 = PFQuery(className: "table1")
let query2 = PFQuery(className: "table2")
let query3 = PFQuery(className: "table3")
let query4 = PFQuery(className: "table4")
let queries = [query1, query2, query3, query4]

queries.forEach { $0.whereKey("question", contains: searchBar.text) }
queries.forEach { (query) in
    query.findObjectsInBackground()
}

The code looks more compact

I hope my answer was helpful 😊

Upvotes: 2

Related Questions