在领域Swift中检索存储的数据

时间:2018-08-25 13:46:33

标签: ios swift realm

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

//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 {

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

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

        return cell
    }

我能够添加到数据库,就像添加到数据库后可以打印一样,但是我对如何检索添加的数据感到困惑。

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

答案 0 :(得分:0)

自从您在此处创建单例

DBManager.instance 

您可以在numberOfRowsInSection

中这样使用它
return  DBManager.instance.getDataFromDB().count

cellForRowAt

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

但这会在每次执行时继续读取数据,因此最好只删除

let realm = try! Realm()

重构为 MVC 时,并在viewDidLoad

中使用它
categoryArray = DBManager.instance.getDataFromDB()

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

相关问题