[英]Retriving stored data in realm Swift
我有一個待辦事項應用程序,正在使用領域來存儲數據。 我已經寫了用於寫入數據庫並檢索的數據庫代碼。 之前,我還以單個頁面代碼的形式處理了這個特定項目,但是現在,我想使用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
}
由於您在這里創建了一個單例
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.