다이어리 앱을 만들면서 기존에 파이어 베이스를 통해 저장하려고 했던 데이터를 소셜 로그인 기능을 제외시키면서 굳이..? 라는 생각이 들어 어차피 로그인이 필요 없으니까 그냥 앱 내에 저장해도 되겠다! 싶어서 전에 봤었던 CoreData를 사용해보게 되었다! (오히려 파이어베이스를 쓰면 인터넷도 되야하니까 더 불편할 것 같다..~!)
CoreData는 UserDefaults를 사용하면서 알게 되었는데, 전에 내가 사용했던 적이 있는 UserDefaults는 간단한 데이터(?)를 저장하는 용도로 사용하고, CoreData는 그보다 더 큰 규모의 데이터를 다룬다고 한다!
음 내가 생각하기에 예를들자면 로그인을 했는지 안했는지에 대한 여부.. 와같은 간단한 정보는 UserDefaults, 그리고 내가 개발중인 다이어리 내 title, contents와 같은 정보들은 그나마 좀 크니까 CoreData로 생각하면 될 것 같다!
예전에 처음 iOS를 배울 때 프로젝트를 생성하는 부분에서
이 화면에 대한 내용을 설명해 주었는데 아래 체크박스 부분은 신경쓰지 말라고 했었다.
근데 이번에 CoreData를 배우면서 저 체크박스의 존재 이유 까지 알게 되었다!
저 체크박스를 체크한 후 프로젝트를 생성하면 나는 CoreData를 사용하겠다고 하고 프로젝트를 생성한다.
그러면 기존에 그냥 생성할 때와 다르게
가장 아래에 요런 파일이 하나 더 생긴다!
그리고 AppDelegate도 약간 다른데,
import UIKit
import CoreData
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "tmp")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
그대로 배껴오자면, CoreData에 해당하는 코드가 추가되고, CoreData가 import 되어있다.
만약 프로젝트를 이미 생성한 후 CoreData를 사용해야 한다면, Command+n을 통해 파일을 추가해주면 된다. (이때 파일 명은 AppDelegate의 container부분의 name과 같아야한다)
https://developer.apple.com/documentation/coredata/setting_up_a_core_data_stack
Apple Developer Documentation
developer.apple.com
위 링크로 이동하면 위와 같은 그림을 확인할 수 있는데, CoreData의 구조이다.
-> 인스턴스는 앱의 유형, 속성 및 관계를 설명하는 앱의 모델 파일을 나타냅니다
-> 인스턴스는 앱 유형의 인스턴스에 대한 변경 사항을 추적합니다
3. NSPersistentStoreCoordinator
-> 스토어에서 앱 유형 의 인스턴스를 저장하고 가져오는 인스턴스입니다.
-> 인스턴스는 모델, 컨텍스트 및 상점 코디네이터를 한 번에 설정합니다.
라고 적혀있는데 ㅎㅎ 난 무슨소리인지 감이 안와서 더 찾아봤다.
간단히 정리해보면
1. 모델파일인 NSManagedObjetContext에서 Persistent Container를 생성한다.
2. entity를 가져온다.
3. NSManagedObject를 만들어 값을 세팅한다.
4. NSManagedObjectContext에 save한다.
처음 해보는거라 감이 잘 안오지만.. CoreData 구조에 기반하여 역할을 생각하며 보면 어렴풋이.. 이해할 수 있을 것 같다.
나는 간단한 구조의 데이터 관리라서 크게 복잡하지 않았는데 더 복잡한 데이터 구조면 많이 고민하고 연습해야겠다..🤔🥺
'iOS > Swift' 카테고리의 다른 글
[iOS/Swift] Convenience init (0) | 2023.04.21 |
---|---|
[iOS] 타입 주석(Type Annotation)과 타입 추론(Type Inference) (0) | 2022.12.27 |
[iOS/swift] navigation controller에서 root view 지정 (스토리보드 구성) (0) | 2022.08.20 |
Reactive X 공부 (0) | 2022.07.19 |
[iOS/Swift] TableView 만들기 (0) | 2022.03.21 |