回调函数未重新加载数据库 [英] Callback function not reloading database

查看:72
本文介绍了回调函数未重新加载数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
    }

推荐答案

从这里开始

写入领域数据库时崩溃

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

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
    }

这篇关于回调函数未重新加载数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆