我正在尝试创建一个待办事项列表应用程序,以在每个类别中添加类别和项目。类别保存在领域数据库中,但根本没有加载。我像修改了我的代码,仍然没有任何显示。 tableview单元格是可单击的,但名称未显示在屏幕上。尽管它仍然保存在领域文件中。如果有人知道解决方案,请帮助我,这是代码。任何帮助表示赞赏
import UIKit
import RealmSwift
class CategoryViewController: UITableViewController {
let realm = try! Realm()
var categories: Results<Category>!
override func viewDidLoad() {
super.viewDidLoad()
loadCategories()
}
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
var textfield = UITextField()
let alert = UIAlertController(title: "Add new Category", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add", style: .default) {
(action) in
let newCategory = Category()
newCategory.name = textfield.text!
self.save(category: newCategory)
}
alert.addAction(action)
alert.addTextField {
(field) in
textfield = field
textfield.placeholder = "Add new Category"
}
present(alert, animated: true, completion: nil)
}
//MARK: - TableView Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "goToItems", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! ToDoListViewController
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedCategory = categories[indexPath.row]
}
}
//MARK: - TableView DataSource Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath)
let category = categories[indexPath.row]
cell.textLabel?.text = category.name
return cell
}
//MARK: - Data Manipulation Methods
func save(category: Category) {
do {
try realm.write {
realm.add(category)
}
}
catch {
print("Error saving category, \(error)")
}
self.tableView.reloadData()
}
func loadCategories() {
categories = realm.objects(Category.self)
tableView.reloadData()
}
}
这些是Category和Item类:...
import Foundation
import RealmSwift
class Category: Object {
dynamic var name: String = ""
let items = List<Item>()
}
import Foundation
import RealmSwift
class Item: Object {
dynamic var title: String = ""
dynamic var done: Bool = false
var parentCategory = LinkingObjects(fromType: Category.self, property: "items")
}
下图是应用程序的情况。
问题是您的领域对象。类别对象的定义如下:
class Category: Object {
dynamic var name: String = ""
let items = List<Item>()
}
它必须是这样,
class Category: Object {
@objc dynamic var name: String = ""
let items = List<Item>()
}
添加@objc将var标记为由Realm管理:
或这样
@objcMembers class Category: Object {
dynamic var name: String = ""
let items = List<Item>()
}
其中@objcMembers使所有由Realm管理的变量。]>