[TIL] iOS CoreData 사용하기

jeongmuyamette·2025년 2월 5일

TIL

목록 보기
39/72
post-thumbnail

[TIL] iOS CoreData 사용하기

1. CoreData란?

CoreData는 iOS 앱에서 데이터를 영구적으로 저장할 수 있게 해주는 프레임워크입니다. SQLite 데이터베이스를 기반으로 하며, 객체 지향적인 방식으로 데이터를 관리할 수 있습니다.

2. CoreData 설정 방법

2.1 Data Model 생성

  1. Xcode에서 Command + N
  2. Data Model 선택
  3. .xcdatamodeld 파일 생성됨

2.2 Entity 설정

// Entity 예시: Todo
Attributes:
- uuid: UUID
- title: String
- content: String
- date: Date
- isCompleted: Boolean

2.3 AppDelegate 설정

lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "모델명")
    container.loadPersistentStores { description, error in
        if let error = error as NSError? {
            fatalError("CoreData 에러: \(error), \(error.userInfo)")
        }
    }
    return container
}()

func saveContext() {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            let error = error as NSError
            fatalError("저장 에러: \(error), \(error.userInfo)")
        }
    }
}

3. CRUD 구현

3.1 CoreDataManager 클래스 생성

final class CoreDataManager {
    static let shared = CoreDataManager()
    private init() {}
    
    private var context: NSManagedObjectContext? {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return nil }
        return appDelegate.persistentContainer.viewContext
    }
}

3.2 Create (생성)

func createTodo(title: String, content: String) {
    guard let context = context else { return }
    guard let entity = NSEntityDescription.entity(forEntityName: "Todo", in: context) else { return }
    
    let todo = NSManagedObject(entity: entity, insertInto: context)
    todo.setValue(UUID(), forKey: "uuid")
    todo.setValue(title, forKey: "title")
    todo.setValue(content, forKey: "content")
    todo.setValue(Date(), forKey: "date")
    todo.setValue(false, forKey: "isCompleted")
    
    do {
        try context.save()
    } catch {
        print("저장 실패: \(error)")
    }
}

3.3 Read (조회)

func fetchTodos() -> [Todo]? {
    guard let context = context else { return nil }
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Todo")
    
    do {
        return try context.fetch(fetchRequest) as? [Todo]
    } catch {
        print("조회 실패: \(error)")
        return nil
    }
}

3.4 Update (수정)

func updateTodo(id: UUID, newTitle: String, newContent: String) {
    guard let context = context else { return }
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Todo")
    fetchRequest.predicate = NSPredicate(format: "uuid = %@", id.uuidString)
    
    do {
        guard let result = try context.fetch(fetchRequest).first as? NSManagedObject else { return }
        result.setValue(newTitle, forKey: "title")
        result.setValue(newContent, forKey: "content")
        try context.save()
    } catch {
        print("수정 실패: \(error)")
    }
}

3.5 Delete (삭제)

func deleteTodo(id: UUID) {
    guard let context = context else { return }
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Todo")
    fetchRequest.predicate = NSPredicate(format: "uuid = %@", id.uuidString)
    
    do {
        guard let object = try context.fetch(fetchRequest).first as? NSManagedObject else { return }
        context.delete(object)
        try context.save()
    } catch {
        print("삭제 실패: \(error)")
    }
}

4. 주의사항

  1. Entity 이름은 반드시 프로젝트에서 유일해야 합니다.
  2. context.save()는 try-catch 구문으로 감싸서 에러 처리를 해야 합니다.
  3. UUID와 같은 고유 식별자를 사용하면 데이터 관리가 용이합니다.
  4. 대용량 데이터 처리시 비동기 처리를 고려해야 합니다.

5. 장점

  • 객체 지향적인 데이터 관리
  • 데이터의 영구 저장
  • 버전 관리 용이
  • 쿼리 최적화

6. 단점

  • 초기 설정이 복잡할 수 있음
  • 러닝 커브가 있음
  • 대용량 데이터 처리시 성능 고려 필요

이상으로 CoreData 사용법에 대한 TIL을 마치겠습니다. 실제 프로젝트에서는 상황에 맞게 수정하여 사용하시면 됩니다.

0개의 댓글