[英]Problem With Realm Saving Using Swift. By mistake, I said "Delete Object" directly From Realm Browser 0
为了测试如果我的 realm 文件中没有任何类别会发生什么,我直接删除了 Realm 浏览器中“类别”的对象。 现在,每当我从我的应用程序添加一个新项目时,它甚至不会在 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 浏览器添加“购物”后:
请记住,我之前也已将对象添加到 realm 文件中,因此即使它没有出现在 realm 文件中,“尚未添加类别”甚至也没有出现......肯定有一些问题。 我没有从调试控制台收到任何错误。
我认为您错误地将“类别”添加到 realm 中。在save() function 中,您只需将“类别”替换为“类别”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.