在领域Swift中检索存储的数据 [英] Retriving stored data in realm Swift

查看:92
本文介绍了在领域Swift中检索存储的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个待办事项应用程序,正在使用领域来存储数据.我已经写了用于写入数据库并检索的数据库代码.之前,我还以单个页面代码的形式处理了这个特定项目,但现在我想使用MVC方法进行改进.这是我的密码.

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

}

数据库模型

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单元格

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

    }

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

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.

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

推荐答案

因为您在此处创建了单例

Since you create a singleton here

DBManager.instance 

您可以在numberOfRowsInSection

return  DBManager.instance.getDataFromDB().count

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

当重构为 MVC 并在viewDidLoad

categoryArray = DBManager.instance.getDataFromDB()

并保留其他部分不变,请注意:在这里,我假设 Category = CategoryModel

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

这篇关于在领域Swift中检索存储的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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