iOS/Swift 어플 따라하기
[Swift] Realm을 사용하여 Data Create(CRUD) + 관계 설정
Chafle
2022. 10. 18. 18:44
반응형
List는 Realm에서 사용하는 array와 가장 비슷한 container type
ex. swift에서의 initialize는
let array : Array<Int> = [1,2,3]
혹은
let array = Array<Int>()
로 initilize할 수 있다
ex Realm에서는
이미 생성된 Item class가 있다면
let items = List<Item>()
요딴식으로 initiailize할 수 있다.
그리고 자동으로 List<Item>()은 일대다 관계를 가진다.
반응형
realm에서의 관계 설정
두 클래스와의 관계에서 정방향 역방향 관계는 직접 설정해줘야 한다.
fromType : Category.self
property: 정방향 관계의 property name
+버튼을 눌러 UIAlert로 data를 Create하는 메서드
@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.categories.append(newCategory)
self.save(category: newCategory)
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Add New Category"
textField = alertTextField
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
func save(category: Category) {
do {
try realm.write{
realm.add(category)
}
} catch {
print("Error saving context \(error)")
}
self.tableView.reloadData()
}
반응형