Callback function not reloading database

坚强是说给别人听的谎言 提交于 2019-12-13 03:22:54

问题


I have an application where I get store and retrieve data from realm. I created a popUp that contains a textfield for input of the data and I also created a callback function that I use to reload the tableview after the save button is clicked but the problem now is the table does not get reloaded when the button is clicked.

AddCategory.swift

 //Callback:- Property that holds a function
var doneSaving: (() -> ())?

@IBAction func saveActionBtn(_ sender: Any) {

        CategoryFunctions.instance.createCategory(name: name, color: color, isCompleted: false)

        if let doneSaving = doneSaving {
            doneSaving()
        }
        dismiss(animated: true, completion: nil)
    }

category.swift

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == Constants.TO_ADD_CATEGORY_VC) {

            let popUp = segue.destination as! AddCategoryVC
            //2 Callback implemented
            popUp.doneSaving = {[weak self] in
                self?.tableView.reloadData()
            }

        }
    }

am I doing anything wrong or what can I do to fix this?

func createCategory(name: String, color: String, isCompleted: Bool) -> Void {

        let category = CategoryModel()
        category.name = name
        category.color = color
        category.isCompleted = false
        DBManager.instance.addData(object: category)

    }

//MARK:- Read Category
    func readCategory(completion: @escaping CompletionHandler) -> Void {


                DBManager.instance.getDataFromDB().forEach({ (category) in
                    let category = CategoryModel()
                    Data.categoryModels.append(category)

                })

    }


func getDataFromDB() -> Results<CategoryModel> {
        let categoryArray: Results<CategoryModel> = database.objects(CategoryModel.self)
        return categoryArray
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: Constants.CATEGORY_CELL) as! CategoryCell
        let category = categoryArray[indexPath.row]
        cell.setup(categoryModel: category)
        return cell
    }

回答1:


Since from here

Crashing on writing to realm database

you only save the data to realm you need to reload it before reloading the table

popUp.doneSaving = {[weak self] in

 self?.tableView.reloadData()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return categoryArray.count
    }


来源:https://stackoverflow.com/questions/52019746/callback-function-not-reloading-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!