在 Realm Swift 中检索存储的数据



我有一个待办事项应用程序,我正在使用 realm 来存储数据。 我已经编写了用于写入数据库和 rerive 的数据库代码。我以前也曾作为单页代码处理过这个特定的项目,但现在我想通过使用 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")
}
}

待办事项列表单元格

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

Todo tableviewcontrollerfunc 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 类别列表.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
}

由于您在此处创建了一个单例

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

并保持其他部分不变,注意:这里我假设类别=类别模型

最新更新