
CoreData는 iOS 앱에서 데이터를 영구적으로 저장할 수 있게 해주는 프레임워크입니다. SQLite 데이터베이스를 기반으로 하며, 객체 지향적인 방식으로 데이터를 관리할 수 있습니다.
Command + N Data Model 선택.xcdatamodeld 파일 생성됨// Entity 예시: Todo
Attributes:
- uuid: UUID
- title: String
- content: String
- date: Date
- isCompleted: Boolean
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)")
}
}
}
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
}
}
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)")
}
}
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
}
}
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)")
}
}
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)")
}
}