LoginSignup
8
8

More than 5 years have passed since last update.

すでに使用している Core Data を App Group で共有する

Last updated at Posted at 2016-05-05

現在使用している Core Data のデータファイルを、App Group で共有するためのフォルダ (shared container) へ移動する必要があります。

手順

  1. App Groupでアプリ間データ共有 などを参考に App Group を有効にする
  2. Core Data のデータファイルを shared container へ移動
    • NSPersistentStoreCoordinator のメソッド migratePersistentStore:toURL:options:withType:error: で移動
    • 移動したら元のファイルは消しておく

データファイル移動の実装例

    func migrate(from: NSURL, to: NSURL) {
        // すでに移動されているかチェック
        guard let path = from.path where NSFileManager.defaultManager().fileExistsAtPath(path) else { return }

        let managedObjectModel = NSManagedObjectModel(contentsOfURL: NSBundle.mainBundle().URLForResource("xxxxx", withExtension: "momd")!)!
        let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)

        let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
        let oldPersistentStore = try! persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: from, options: options)
        try! persistentStoreCoordinator.migratePersistentStore(oldPersistentStore, toURL: to, options: nil, withType: NSSQLiteStoreType)

        try! NSFileManager.defaultManager().removeItemAtPath(path)
    }


    let oldStoreUrl = xxxxx
    let newStoreUrl = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.xxxxx")!.URLByAppendingPathComponent("xxxxx.sqlite")

    migrate(oldStoreUrl, to: newStoreUrl)

環境

Xcode 7.3
Swift 2.2

参考

ios - coredata - move to app group target - Stack Overflow

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8