Retriving stored data in realm Swift

浪尽此生 提交于 2019-12-11 14:33:48

问题


I have a todo application which I am using realm to store data. i have writen the database codes for writing to the database and retrive. I have also worked on this particular project before in as a single page code but now I want to improve it by using the MVC approach. this is my codes.

//MARK:- Create Category
func createCategory(name: String, color: String, isCompleted: Bool) -> Void {

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

}

Database model

private init() {
        database = try! Realm()
    }

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


    func addData(object: CategoryModel)   {
        try! database.write {
            database.add(object, update: true)
            print("Added new object")
        }
    }

TodoList Cell

func setup(categoryModel: CategoryModel) -> Void {
        categoryNameLabel.text = categoryModel.name

    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: Constants.CATEGORY_CELL) as! CategoryCell

        cell.setup(categoryModel: Data.categoryModels[indexPath.row])

        return cell
    }

I am able to add to the database as I can print after adding to the database but I am confused as to how to retrieve the added data.

Without MVC categorylist.swift

let realm = try! Realm()

var categoryArray : Results<Category>?
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        //nil coalising operator
        return Data.categoryModels.count
    }


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

        //tapping into the super class
        let cell = super.tableView(tableView, cellForRowAt: indexPath)

        if let category = categoryArray?[indexPath.row] {
            cell.textLabel?.text = "#\(category.name)"
            guard let categoryColor = UIColor(hexString: category.color) else {fatalError()}
            cell.backgroundColor = categoryColor
            cell.textLabel?.textColor = ContrastColorOf(categoryColor, returnFlat: true)
        }

        return cell
    }

回答1:


Since you create a singleton here

DBManager.instance 

you can use it like this inside numberOfRowsInSection

return  DBManager.instance.getDataFromDB().count

and inside cellForRowAt

let item = DBManager.instance.getDataFromDB()[indexPath.row]

but this will keep reading the data every execute , so it's better to remove only

let realm = try! Realm()

when refactor to MVC , and use this inside viewDidLoad

categoryArray = DBManager.instance.getDataFromDB()

and leave the other parts unchanged , note: here i assume that Category = CategoryModel



来源:https://stackoverflow.com/questions/52017908/retriving-stored-data-in-realm-swift

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