回调函数未重新加载数据库

时间:2018-08-25 17:41:49

标签: ios swift realm

我有一个应用程序,可以在其中存储和从领域检索数据。我创建了一个包含用于输入数据的文本字段的弹出窗口,还创建了一个回调函数,该函数用于单击保存按钮后重新加载表格视图,但是现在的问题是单击该按钮时无法重新加载表格。

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()
            }

        }
    }

我做错了什么或者我该怎么解决?

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 个答案:

答案 0 :(得分:1)

从这里开始

Crashing on writing to realm database

您只将数据保存到领域,然后才需要重新加载表

popUp.doneSaving = {[weak self] in

 self?.tableView.reloadData()
}

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

        return categoryArray.count
    }