@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New Category", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Category", style: .default) { (action) in
let newCategory = Category()
newCategory.name = textField.text!
self.categories.append(newCategory)
self.save(category: newCategory)
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Category Name"
textField = alertTextField
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
func save(category: Category) {
do {
//try context.save()
try realm.write {
realm.add(category)
}
} catch {
print("Error saving new category : \(error)")
}
self.tableView.reloadData()
}
→ realm.write { } can throw an error, just like context.save( ) does with Core Date. Thus, we need to put it inside a do-catch statement.
// TodoListViewController
var selectedCategory: Category? {
didSet {
loadItems()
}
}
...
if let currentCategory = self.selectedCategory {
do {
try self.realm.write {
let newItem = Item()
newItem.title = textField.text!
newItem.isDone = false
currentCategory.items.append(newItem)
}
} catch {
print("Error saving new items \(error)")
}
}
self.tableView.reloadData()
}
// Item.swift
class Category: Object {
@objc dynamic var name: String = ""
let items = List<Item>()
}