iOS & Swift 공부 - Realm -> How to Save Data Using Realm (Create in CRUD)

김영채 (Kevin)·2021년 3월 18일
0

iOS & Swift

목록 보기
97/107
post-thumbnail

  • First, setup the necessary Data files in your project directory.
  • The class you set up must be a subclass of "Object", which is a class used to define Realm model objects.
  • The properties of such class must have "@objc dynamic" declaration modifiers, so that Realm can detect changes of those variables during runtime.

  • So each "Category" has a 1-to-many relationship with a List of Items.
  • However, Realm does not define the inverse relationship automatically.
  • For instance, in a Todo App, each category will have a separate array of (todo) items. To declare this relationship, we can use a class called "List", which is the container type in Realm used to define to-many relationships.

  • Here, we can see that each Item has an inverse relationship to a Category called the parentCategory. So, each Item has a parentCategory.

  • Initialize Realm for usage. Making a Realm( ) instance is essential for every class file.
@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.

  • real.write { } is like saying, "we are beginning to write". The real part where we actually add data to the Realm data base is the realm.add( ) part.
// 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>()
}
  • Notice we are "appending" in this case. But we are not appending to the Item data type. We are tapping in to the currently selected category.
profile
맛있는 iOS 프로그래밍

0개의 댓글