iOS & Swift 공부 - Realm -> Update, Delete, Querying Data Using Realm

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

iOS & Swift

목록 보기
99/107
post-thumbnail

Updating Data Using Realm (Update in CRUD)


  • Updating in Realm is very similar to creating a new item.
var todoItems: Results<Item>?

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    if let item = todoItems?[indexPath.row] {
            
        do {
            try realm.write {
                item.isDone = !item.isDone
            }
        } catch {
            print("Error in didSelectRowAt : \(error)")
        }
    }
    tableView.reloadData()
    tableView.deselectRow(at: indexPath, animated: true)    // cell 을 누르자마자 deselect 되는 애니메이션이 나올 수 있도록
}

→ We first have to unwrap the Results container and see if it is not nil.

Deleting Data Using Realm (Delete in CRUD)


override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    if let item = todoItems?[indexPath.row] {
            
        do {
            try realm.write {
                    
                realm.delete(item)
                //item.isDone = !item.isDone
            }
        } catch {
            print("Error in didSelectRowAt : \(error)")
        }
    }
   tableView.reloadData()
   tableView.deselectRow(at: indexPath, animated: true)    // cell 을 누르자마자 deselect 되는 애니메이션이 나올 수 있도록
}

realm.delete ( object )

Querying Data Using Realm


//MARK: - UISearchBarDelegate

searchBar.delegate = self

extension TodoListViewController: UISearchBarDelegate {

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        
        todoItems = todoItems?.filter("title CONTAINS[cd] %@", searchBar.text!).sorted(byKeyPath: "dateCreated", ascending: true)
        
        tableView.reloadData()
		}  
}
profile
맛있는 iOS 프로그래밍

0개의 댓글