iOS & Swift 공부 - Realm -> Reading Data Using Realm (Read in CRUD)

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

iOS & Swift

목록 보기
98/107
post-thumbnail

Reading Data Using Realm (Read in CRUD)


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>?
  • A special thing about the Results container in Realm, is that it is an auto-updating container type.

    → What this means is that we won't have to "append" new elements to the array explicitly using the append function.
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!

profile
맛있는 iOS 프로그래밍

0개의 댓글