func loadCategories() {
categories = realm.objects(Category.self)
tableView.reloadData()
}
→ Unlike Core Data, fetching Realm objects is really simple, because it only requires 1 line.
If you want to fetch a Category type object, just specify it like the code above, but just remember to specify ".self" after the class name.
Also, since realm.object ( ) return a type of "Results", the "categories" must also be in this format.
var categories: Results<Category>?
let newCategory = Category()
newCategory.name = textField.text!
//self.categories.append(newCategory)
// The above code is not needed
self.save(category: newCategory)
func save(category: Category) {
do {
try realm.write {
realm.add(category)
}
} catch {
print("Error saving new category : \(error)")
}
self.tableView.reloadData()
}
In fact, the Result container type doesn't even support the "append" method.
→ As long as you saved the updated element to Realm, you don't have to explicitly append the new element to the array.
→ It's auto-updated!