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