오늘은 iOS에서 쓰이는 데이터 저장 방식인 CoreData를 공부했다.
🔹 사용 예시:
// 예시 코드 (실제 구현 시 Entity 설정 및 Context 관리 필요)
let newItem = NSEntityDescription.insertNewObject(forEntityName: "Person", into: context)
newItem.setValue("Ash", forKey: "name")
try? context.save()
import UIKit
import CoreData
class ViewController: UIViewController {
var container: NSPersistentContainer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .red
let appDelegate = UIApplication.shared.delegate as! AppDelegate
self.container = appDelegate.persistentContainer
createData(name: "Adam1", phoneNumber: "010-1111-2222")
readAllData()
}
func createData(name: String, phoneNumber: String) {
guard let entity = NSEntityDescription.entity(forEntityName: "PhoneBook1", in: self.container.viewContext) else { return }
let newPhoneBook = NSManagedObject(entity: entity, insertInto: self.container.viewContext)
newPhoneBook.setValue(name, forKey: "name")
newPhoneBook.setValue(phoneNumber, forKey: "phoneNumber")
do {
try self.container.viewContext.save()
print("문맥 저장 성공")
} catch {
print("문맥 저장 실패")
}
}
func readAllData() {
do {
let phoneBooks = try self.container.viewContext.fetch(PhoneBook1.fetchRequest())
for phoneBook in phoneBooks as [NSManagedObject] {
if let name = phoneBook.value(forKey: "name") as? String,
let phoneNumber = phoneBook.value(forKey: "phoneNumber") {
print("name: \(name), phoneNumber: \(phoneNumber)")
}
}
} catch {
print("데이터 읽기 실패")
}
}
}

var container: NSPersistentContainer!NSPersistentContainer는 CoreData의 저장소 전체를 관리하는 객체."CoreData 전체를 다루는 커다란 상자(container)를 만들 거야."
let appDelegate = UIApplication.shared.delegate as! AppDelegateUIApplication.shared.delegate는 앱 전체에서 공유된 델리게이트 객체를 가져오는 거고,AppDelegate 타입으로 형변환하고 있어."앱 전체를 관리하는 AppDelegate를 가져와서 사용할 준비를 해!"
self.container = appDelegate.persistentContainerpersistentContainer를 가져와서self.container에 연결한 거야."AppDelegate에서 만들어 둔 CoreData 컨테이너를 내 클래스에서도 쓸 수 있게 저장!"
CoreData를 활성화 하면 아래의 코드가 생긴다.
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "MyModel") // .xcdatamodeld 파일 이름
container.loadPersistentStores { _, error in
if let error = error {
fatalError("CoreData 로딩 실패: \(error)")
}
}
return container
}()
"MyModel"이라는 이름의 데이터 모델을 로드함.| 코드 | 설명 |
|---|---|
var container | CoreData 저장소 전체를 관리하는 객체 선언 |
UIApplication.shared.delegate | 앱의 공통 관리자(AppDelegate)에 접근 |
appDelegate.persistentContainer | CoreData의 실질적인 저장소(컨테이너)를 가져옴 |
NSEntityDescription은 말 그대로 그 Entity(테이블 구조)에 대한 설명을 담당하는 클래스"PhoneBook1이라는 테이블의 설계도(틀, 구조)를 알려줘!" 라고 할 때 사용하는 게
NSEntityDescription
NSEntityDescription.entity(forEntityName: "PhoneBook1", in: self.container.viewContext)
in: 은 어느 공간(Context) 안에서 찾을지 정해주는 것."viewContext 안에 정의된 'PhoneBook1' 테이블 구조 좀 줘!"
이건 CoreData의 저장소에 접근할 수 있는 통로야. 두 개로 나눠서 설명할게.
containercontainer는 NSPersistentContainer라는 타입"container는 데이터베이스 전체 박스야"
viewContextcontainer 안에는 데이터를 실제로 읽고 쓰는 작업 공간이 필요함.viewContextContext."viewContext는 데이터 넣고 꺼내는 책상 같은 공간"
container는 CoreData 데이터베이스 전체고,viewContext는 현재 화면에서 그걸 읽고 쓰기 위한 도구야."
guard let entity = NSEntityDescription.entity(forEntityName: "PhoneBook1", in: self.container.viewContext) else { return }
PhoneBook1이라는 Entity를 가져오는 코드self.container.viewContext: 실제 저장/불러오는 공간(문맥, context)let newPhoneBook = NSManagedObject(entity: entity, insertInto: self.container.viewContext)
newPhoneBook이라는 새 객체를 만든다. newPhoneBook.setValue(name, forKey: "name")
newPhoneBook.setValue(phoneNumber, forKey: "phoneNumber")
setValue()는 데이터를 저장할 때 쓰는 메서드"name"이라는 속성에 name 값 넣기"phoneNumber" 속성에 phoneNumber 값 넣기do {
try self.container.viewContext.save()
print("문맥 저장 성공")
} catch {
print("문맥 저장 실패")
}
do-try-catch 사용| 용어 | 의미 |
|---|---|
NSEntityDescription | CoreData의 테이블 구조를 정의한 클래스 |
.entity(forEntityName:in:) | 특정 이름의 테이블 구조를 특정 저장소(context) 안에서 가져오는 메서드 |
container | CoreData 전체를 관리하는 박스 (NSPersistentContainer) |
viewContext | 데이터를 저장하거나 불러올 때 사용하는 CoreData의 실행 공간 |
NSManagedObject | 객체(Object) 형태로 데이터를 저장하고 관리할 수 있게 해주는 프레임워크. |
setValue() | 각 칸에 값 채우기 |
viewContext.save() | 실제로 디스크에 저장 |