티스토리 뷰

지난 번에 UserDefaults에 값을 셋팅하고, 불러오는 간단한 메서드를 알아보았는데여?

오늘은 간단하게 UserDefaults를 통해 저장한 값을 테이블뷰로 불러오도록 해보려구요.

(다른 공부 안했다고 말 모대,,,ㅎ)

 


우선 아주 간단한 프로젝트를 하나 만들어줄게요.

추가 버튼을 누르면 alert 창이 뜨고, 거기에 추가한 textField가 테이블뷰에 보여지는 고런 간단한?

 

(운동하기에서 제법 망설인 편,,ㅎ)

기본 코드는 접어둘게요!!⭐️

더보기
import UIKit

class ViewController: UIViewController {
    
    let tableView = UITableView()
    let addBtn = UIButton()
    var itemArray: [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureUI()
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }
}

//MARK: -Event
extension ViewController {
    @objc func addBtnTapped(_ sender: UIButton) {
        var myTextField = UITextField()
        let alert = UIAlertController(title: "오늘의 할일", message: "", preferredStyle: .alert)
        let action = UIAlertAction(title: "할 일 추가", style: .default) { (action) in
            self.itemArray.append(myTextField.text ?? "")
            self.tableView.reloadData()
        }
        alert.addTextField { (alertTextField) in
            myTextField = alertTextField
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }
}


//MARK: -UITableViewDelegate, UITableViewDataSource
extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return itemArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! UITableViewCell
        cell.textLabel?.text = itemArray[indexPath.row]
        return cell
    }
}

//MARK: -UI
extension ViewController {
    final private func configureUI() {
        setConstraints()
        setAttributes()
        addTarget()
    }
    
    final private func setAttributes() {
        addBtn.setTitle("추가", for: .normal)
        addBtn.setTitleColor(.blue, for: .normal)
    }
    
    final private func addTarget() {
        addBtn.addTarget(self, action: #selector(addBtnTapped(_:)), for: .touchUpInside)
    }

    final private func setConstraints() {
        [addBtn, tableView].forEach {
            view.addSubview($0)
            $0.translatesAutoresizingMaskIntoConstraints = false
        }
        NSLayoutConstraint.activate([
            addBtn.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 30),
            addBtn.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
            
            tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            tableView.topAnchor.constraint(equalTo: addBtn.topAnchor, constant: 30),
            tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
        ])
    }
}

만약! 제가 여기서 스와이프해서 앱을 꺼버렸다가 다시 키면 어떻게 될까요?

날라갔네여 ㅎㅎㅎㅎ운동하기 싫었는데, 잘된건가?ㅎㅎ (헛소리 지송해여)

그럼 저 간단한 목록들을 UserDefaults를 통해 저장하고, 앱을 껐다 키더라도 다시 불려질 수 있도록 해볼까요?


우선 viewDidLoad 위에 UserDefaults의 객체를 하나 만들어줍니당.

let defaults = UserDefaults.standard

 

그럼 이제 지난 번에 공부한 것처럼 set메서드를 이용해서 할 일 목록을 저장하면 되겠는데,,,

어느 시점에 하는 게 맞을까요?

 

alert창에서 "할 일 추가" 버튼을 눌렸을 때, 추가된 리스트까지 더해지는 게 맞겠져?

그러면 해당 클로저에서 작업을 해볼게요.

extension ViewController {
    @objc func addBtnTapped(_ sender: UIButton) {
        var myTextField = UITextField()
        let alert = UIAlertController(title: "오늘의 할일", message: "", preferredStyle: .alert)
        let action = UIAlertAction(title: "할 일 추가", style: .default) { (action) in
            self.itemArray.append(myTextField.text ?? "")
            //⭐️⭐️⭐️
            self.defaults.set(self.itemArray, forKey: "ToDoList")
            self.tableView.reloadData()
        }
        alert.addTextField { (alertTextField) in
            myTextField = alertTextField
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }
}

alert의 textField까지 추가된 itemArray를 UserDefaults에 저장해요.

근데, 앱을 껐다가 다시 켰을 때 어떻게 UserDefaults에 저장된 값을 다시 tableView에 불러올까요?

 

 

그건 view가 DidLoad될 때, UserDefaults의 list를 다시 가져오면 되는데, 지난 번 글에서 UserDefaults를 가져올 때 썼던 메서드를 쓰면 됩니당.

Array 타입이기 때문에, 아래 메서드를 사용해줄게요.

 

    override func viewDidLoad() {
        super.viewDidLoad()
        configureUI()
        
        //⭐️⭐️⭐️
        if let items = defaults.array(forKey: "ToDoList") as? [String] {
            itemArray = items
        }
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

return 타입이 옵셔널이기 때문에 옵셔널 바인딩과 타입 캐스팅도 함께 해줍니다.

그리고 그 배열을 다시 itemArray에 넣어주면 view가 로드될 때, UserDefault의 값이 불러지겠져?

앱을 종료했다 다시 실행해도 그대로인 걸 확인할 수 있다리!!

 


이 후 2개 정도 할 일을 추가했는데여!!

이 리스트가 UserDefaults에 어떤 식으로 저장되어 있는지 볼까요?

제가 아까 설정했던 key("ToDoList")로 해당 배열이 저장되어 있는 게 보이시져?

여기에 저장된 값을 앱이 실행될 때마다 불러오는 거에요!

 


 

근데 저 파일 경로는 didFinishLaunchingWithOptions에 아래 프린트문을 넣어서 얻어낸 경로인데요. (강의에서 배움)

//AppDelegate.swift
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        print(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String)
        return true
    }

만약 마지막 경로가 Documents로 나와서 plist가 확인이 안되시면 Documents가 아닌 Library/Preferences 폴더로 가면 있을거에요!


 

근데 첫 번째 글에서 말했듯이 UserDefaults는 아주 작은 데이터들만 저장(음악 볼륨, 음악 on/off, 최고점수 등)하기에 적당하기 때문에, 해당 연습은 그냥 참고만 해주십셔!

 

틀린 게 있으면 언제나 지적 부탁드림돠 슨배님덜!!🙏🏻

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크