[swift] 코어 데이터와 UI 간의 연동

코어 데이터(Core Data)는 iOS 앱 개발에 자주 사용되는 데이터베이스로, 데이터를 저장하고 관리하는데 도움을 줍니다. 이 글에서는 코어 데이터와 UI 간의 연동에 대해 알아보겠습니다.

1. 코어 데이터 설정

먼저, Xcode에서 프로젝트를 생성한 후, 코어 데이터를 설정해야 합니다. 아래의 단계를 따라주세요.

  1. 프로젝트 내에서 .xcdatamodeld 파일을 생성합니다.
  2. 생성된 파일을 열고, 엔터티를 추가하고 필요한 속성을 정의합니다.
  3. 엔터티 간의 관계를 설정합니다.
  4. 해당 파일을 저장한 후, Xcode가 자동으로 생성한 클래스 파일을 확인합니다.

2. 데이터 가져오기

코어 데이터를 사용하여 데이터를 가져오는 방법은 다양합니다. 여기에서는 예시를 통해 간단히 알아보겠습니다.

import CoreData

// 코어 데이터 컨텍스트 가져오기
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let context = appDelegate.persistentContainer.viewContext

// 쿼리 생성
let fetchRequest: NSFetchRequest<EntityName> = EntityName.fetchRequest()

do {
    // 데이터 가져오기
    let result = try context.fetch(fetchRequest)
    
    for data in result {
        // 데이터 사용
        let name = data.name
        let age = data.age
        print("Name: \(name), Age: \(age)")
    }
} catch {
    print("Error fetching data: \(error)")
}

위의 코드에서 EntityName은 코어 데이터 모델에서 정의한 엔터티의 이름으로 대체해야 합니다. 데이터를 가져오기 위해 fetchRequest를 생성하고, context.fetch를 호출하여 데이터를 가져옵니다.

3. UI에 데이터 반영하기

가져온 데이터를 UI에 반영하는 방법은 앱의 구조와 디자인에 따라 다를 수 있습니다. 여기서는 UITableView를 사용한 예시를 보여드리겠습니다.

class ViewController: UIViewController, UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    
    var data: [EntityName] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.dataSource = self
        
        // 데이터 가져오기
        fetchData()
    }
    
    // 데이터 가져오기
    func fetchData() {
        // 코어 데이터 컨텍스트 가져오기
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        let context = appDelegate.persistentContainer.viewContext
        
        // 쿼리 생성
        let fetchRequest: NSFetchRequest<EntityName> = EntityName.fetchRequest()
        
        do {
            // 데이터 가져오기
            data = try context.fetch(fetchRequest)
            
            // 테이블 뷰 리로드
            tableView.reloadData()
        } catch {
            print("Error fetching data: \(error)")
        }
    }
    
    // 테이블 뷰 데이터 소스 메소드
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        let item = data[indexPath.row]
        cell.textLabel?.text = item.name
        
        return cell
    }
    
}

위의 코드에서 EntityName은 코어 데이터 모델에서 정의한 엔터티의 이름으로 대체해야 합니다. fetchData() 메소드에서 데이터를 가져오고, tableView.reloadData()를 호출하여 테이블 뷰를 업데이트합니다.

이제 위의 예시를 참고하여 코어 데이터와 UI를 간단히 연동하는 방법을 알아보았습니다. 코어 데이터를 활용하여 앱의 데이터를 효율적으로 관리하고 UI에 반영할 수 있습니다.