To test out what would happen if there weren't any categories in my realm file, I directly deleted the objects for "Categories" in the Realm browser. Now, whenever I add a new item from my app, it doesn't even register in the Realm browser.
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)
}
}
When I Am Adding Something Called "Shopping" To My Categories:
After I Click The Add Button:
My Realm Browser After I already Added "Shopping":
Keep in mind, that I have added objects into the realm file before too, so even though it doesn't show up in the realm file, the "No Categories Added Yet" doesn't even show up... There is definitely some issue. I don't get any errors from the debug console.
I think by mistakenly you are adding "categories" into realm. In save() function, you just need to replace "categories" with "category".