我有一个 todo 应用程序,我正在使用领域来存储数据。我已经编写了用于写入数据库并检索的数据库代码。我之前也曾作为单页代码处理过这个特定项目,但现在我想通过使用 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句