티스토리 뷰

728x90

 

gist.github.com/atomicbird/25fed73657be4b9d3642981a4892fea4

 

Back up and restore Core Data persistent stores

Back up and restore Core Data persistent stores. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

core data를 백업하고 복원하는데 필요한 NSPersistentContainer 를 확장하는 코드는 위 링크에 있다.

너무 자료가 없어서.. 난 그냥 원문 읽어가면서 했는데 혹시 나같은 사람있을까봐 써둡니다.

www.atomicbird.com/blog/core-data-back-up-store/

 

Backing up Core Data Stores

Today we’re going to travel back in time a little with Core Data. Or at least find out how your app can do so. What if you want to make a backup copy of your app’s data? What if you want to restore from that backup later on? This won’t be mainly abou

atomicbird.com

설명은 이 블로그에 자세히 돼있으니 참고할 분들은 참고하세요

 

프로젝트 내의 core data가 import 되어있는 아무 파일에 해당 코드를 추가하고 

 

func copyPersistentStores(to destinationURL: URL, overwriting: Bool = false) throws -> Void 
func restorePersistentStore(from backupURL: URL) throws -> Void

 

persistentContainer는 appdelegate에 초기화 돼있을거고

appdelegate는 core data를 쓰고있다면 appdelegate를 참조하는 변수를 만들어 두었을테니

사용할땐

 

try appdelegate.persistentContainer.copyPersistentStores(to: {copied 파일을 저장해둘 디렉토리 경로 = 아이클라우드 앱 폴더 경로}, overwriting: true)
try appDelegate.persistentContainer.restorePersistentStore(from: {copy한 경로})

 

이렇게 사용해주면 된다.

여기서 아이클라우드 경로는 

let icloudURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("폴더명")

 

*아이클라우드가 아니라도 local document에 접근하려면

info.plist 에 Supports Document Browser 키를 추가해주고 type boolean, value YES로 설정해줘야한다.

 

이렇게 설정해주면 아이클라우드 드라이브 내 앱 폴더 안에 입력해준 폴더명에 sql 파일 3개가 저장되는걸 볼 수 있다.

복원 함수에 같은 경로를 넣어주면 그곳에서 파일을 받아와서 데이터가 덮어쓰기 된 것 처럼 작동한다.

*icloud drive에 저장하려면 개발자 등록이 되어있어야 한답니다 (연 멤버십 12만원..매년 갱신..그래라..)

 

let documentURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let dataURL = documentURL.appendingPathComponent("폴더명")

 

icloud가 아니라 그냥 로컬(내 iphone)에 파일을 저장하려면 위와 같은 코드를 써주고

경로에 icloudURL대신 dataURL을 입력해주면 된다.

하지만 이 방법은 로컬에만 저장되기 때문에 핸드폰을 바꾼다거나 다른 기기에서 데이터를 복원 받고자할때는

일일이 파일을 옮기거나 해야한다는거 (이렇게 한다고 해도 동일한 폴더명에 저장돼있어야 하고)

 

아직까지 core data 쓰는 사람이 그렇게 많지는 않은지 관련 한글 자료가 너무 없어서 적어두는거 반 내가 까먹을까봐 적어두는거 반

도움이 됐길 바랍니다 😊

728x90
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함