포스트

Todoey (7)

TodoList VC

이제 TodoList VC도 CategoryVC와 같이 수정을 해보도록 하자.

context는 이제 안쓰니 지워버리자.

1. loadItems 수정

기존에 Parameter로 있던 request부분을 전부 날려버리자.

그리고 itemArray에 itemArray = selectedCategory?.items.sorted(byKeyPath: "title", ascending: true) 이렇게 Realm을 활용하는 코드로 바꿔준다.

위의 내용은 request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)] 이부분과 동일하다고 보면된다.

title이라는 field를 기준으로 내림차순을 한다는것.

다시 itemArray로 돌아가서

1
2
3
4
5
// before
var itemArray = [Item]()

// after
var itemArray: Results<Item>?

2. Optional Binding

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath)
        
        if let item = todoItems?[indexPath.row] {
            cell.textLabel?.text = item.title
            
            cell.accessoryType = item.done ? .checkmark : .none
        } else {
            cell.textLabel?.text = "No Items Added"
        }
        
        return cell
    }

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return todoItems?.count ?? 1
    }    

3. SaveItems 구현

selectedCategory가 nil이 아니라면~

1
2
3
4
5
6
7
8
9
10
11
12
if let currentCategory = self.selectedCategory {
                do {
                    try self.realm.write{
                        let newItem = Item()
                        newItem.title = textField.text!
                        currentCategory.items.append(newItem)
                    }
                } catch {
                    print("Error Saving New Items, \(error.localizedDescription)")
                }
                
            }

currentCategory에 item을 담아주면서 relationship과 매칭

CleanShot 2024-04-15 at 13 28 44@2x

결과. 연결이 잘되었다.

그리고 load할때 title로 sorting을 하게 해두었기에,

simulator_screenshot_6FC814CA-B251-4337-894C-002344F72D7D

이렇게 정렬된 모습으로 볼 수 있다.

CRUD중 Update 구현

Save 메커니즘과 유사하기에 크게 차이점은 없다.

didSelectRowAt의 함수에서 수정할수있게 구현 할것이다.

선택한 아이템이 존재한다면?

해당 셀을 터치했을때 완료에대한 내용이 수정이되게 간단하게 바꾸었다.

1
2
3
4
5
6
7
8
9
10
if let item = todoItems?[indexPath.row] {
            do {
                try realm.write {
                    item.done = !item.done
                }
            } catch {
                print("Error Saving New Items, \(error.localizedDescription)")
            }
            
        }

실행했을때 true면 checkmark가 뜨게 될것이다.

Apr-15-2024 13-37-19

실시간으로 변하는것도 확인 완료.

CRUD중 Delete 구현

이번엔 셀을 클릭했을때 삭제하게 만들어 보자.

1
2
3
4
5
6
7
8
9
10
11
if let item = todoItems?[indexPath.row] {
            do {
                try realm.write {
                    realm.delete(item)
                    //item.done = !item.done
                }
            } catch {
                print("Error Saving New Items, \(error.localizedDescription)")
            }
            
        }

delete에 해당 item을 해주면된다.

크게 어려운부분은 없다.

Apr-15-2024 13-41-08

구현 완료.

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.