【发布时间】:2020-05-15 16:23:06
【问题描述】:
为了测试如果我的领域文件中没有任何类别会发生什么,我直接删除了领域浏览器中“类别”的对象。现在,每当我从我的应用中添加新项目时,它甚至都不会在 Realm 浏览器中注册。
import UIKit
import CoreData
import RealmSwift
class CategoryViewController: UITableViewController {
let realm = try! Realm()
var categories: Results<Category>?
override func viewDidLoad() {
super.viewDidLoad()
loadCategory()
}
// MARK: - Table View Datasource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories?.count ?? 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for : indexPath)
cell.textLabel?.text = categories?[indexPath.row].name ?? "No Categories Added Yet!"
return cell
}
// MARK: - Table View Delegate
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.selectCategory = categories![indexPath.row]
}
}
// MARK: - Data Manipulation Methods
func save(category: Category) {
do {
try realm.write {
realm.add(categories!)
}
} catch {
print("There was an error saving context, \(error.localizedDescription)")
}
tableView.reloadData()
}
func loadCategory() {
categories = realm.objects(Category.self)
tableView.reloadData()
}
@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 A New Category"
}
present(alert, animated: true, completion: nil)
}
}
当我在我的类别中添加称为“购物”的内容时:
点击添加按钮后:
添加“购物”后的我的 Realm 浏览器:
请记住,我之前也将对象添加到领域文件中,所以即使它没有出现在领域文件中,“还没有添加类别”甚至没有出现......那里绝对是一些问题。我没有从调试控制台收到任何错误。
【问题讨论】:
-
大家好,如果您能帮我解决这个问题,我将不胜感激......再次非常感谢......
-
感谢 Tyler 让这个问题更具可读性!
-
Hmmm.... 看到这个
realm.add(categories!)你保存了 empty 类变量,而它应该是这个realm.add(category) -
嘿,非常感谢杰伊的帮助!它有效!