App Group Capability는 여러 개의 앱(또는 앱과 해당 확장 프로그램)이 데이터를 공유할 수 있도록 해주는 Sandbox 환경 내의 컨테이너 공유 기능이다.
✅ 주요 목적:
✅ 설정 방법:
1. App Group 활성화
group.com.yourcompany.sharedData
) UserDefaults
(App Group을 지원하는 별도 인스턴스 사용) FileManager
(공유된 폴더 사용) CoreData
(공유된 Store 파일 사용) 특성 | Core Data | UserDefaults |
---|---|---|
사용 목적 | 대량의 데이터, 복잡한 구조 | 간단한 설정값, 작은 데이터 |
데이터 구조 | 테이블 형식, 관계형 데이터 | Key-Value 저장 방식 |
저장 공간 | SQLite 데이터베이스 파일 | plist 파일 (XML 기반) |
App Group 지원 | ✅ 가능 (공유된 컨테이너 내 저장) | ✅ 가능 (App Group용 UserDefaults 사용) |
성능 | 대량 데이터에 적합 (인덱싱, 검색 최적화) | 빠름 (단순 Key-Value 접근) |
데이터 공유 방식 | NSPersistentContainer 를 사용하여 App Group 경로에 저장 | UserDefaults(suiteName:) 을 사용하여 App Group에 저장 |
동기화 지원 | iCloud Sync 가능 | iCloud Key-Value Storage 지원 |
App Group 환경에서 UserDefaults를 공유하려면 suiteName
을 지정해야 한다.
let sharedDefaults = UserDefaults(suiteName: "group.com.yourcompany.sharedData")
// 데이터 저장
sharedDefaults?.set("Hello, App Group!", forKey: "sharedKey")
// 데이터 가져오기
if let sharedValue = sharedDefaults?.string(forKey: "sharedKey") {
print("Shared Value: \(sharedValue)")
}
🟢 언제 사용하면 좋을까?
CoreData는 기본적으로 앱별로 개별적인 SQLite
파일을 사용하지만, App Group을 활용하면 공유 저장소에 저장 가능하다.
✅ 1. 공유 컨테이너 경로 가져오기
import CoreData
// App Group을 위한 CoreData 저장 경로 설정
let container = NSPersistentContainer(name: "SharedModel")
if let storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.yourcompany.sharedData")?.appendingPathComponent("SharedStore.sqlite") {
let storeDescription = NSPersistentStoreDescription(url: storeURL)
container.persistentStoreDescriptions = [storeDescription]
}
✅ 2. 데이터 저장 예제
func saveData(name: String) {
let context = container.viewContext
let newEntity = SharedEntity(context: context)
newEntity.name = name
do {
try context.save()
print("Data saved successfully!")
} catch {
print("Failed to save: \(error)")
}
}
🟢 언제 사용하면 좋을까?
사용 시나리오 | 추천 저장 방식 |
---|---|
단순한 Key-Value 데이터 (설정 값, 작은 데이터) | ✅ UserDefaults(suiteName:) |
대량의 데이터, 검색/필터링 필요 | ✅ CoreData (App Group 저장소 활용) |
파일 저장 (이미지, 문서 등) | ✅ FileManager (App Group 폴더 활용) |