iOS 11+ How to migrate existing Core Data to Shared App Group for use in extension?

前端 未结 3 606
北荒
北荒 2020-12-09 06:23

When I created an iOS 11 app using the core data template, it auto generated the following code in AppDelete.m.

synthesize persistentContainer = _persistentC         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 06:51

    UPDATE:

    To migrating an existing persistent store, the NSPersistentContainer contains the persistentStoreCoordinator, an instance of NSPersistentStoreCoordinator. This exposes the method migratePersistentStore:toURL:options:withType:error: to migrate a persistent store.

    I would do the following:

    // Get the reference to the persistent store coordinator
    let coordinator = persistentContainer.persistentStoreCoordinator
    // Get the URL of the persistent store
    let oldURL = persistentContainer.persistentStoreDescriptions.url
    // Get the URL of the new App Group location
    let newURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("YOUR_APP_GROUP")
    // Get the reference to the current persistent store
    let oldStore = coordinator.persistentStore(for: oldURL)
    // Migrate the persistent store
    do {
       try coordinator.migratePersistentStore(oldStore, to: newURL, options: nil, withType: NSSQLiteStoreType)
    } catch {
       // ERROR
    }
    

    Please note that the above hasn't been tested and I haven't handled Optionals so it isn't complete. Also, I apologise for it being in Swift. Hopefully it is easy enough for you to write the equivalent in Objective-C.

    ORIGINAL:

    The following outlines how to create an NSPersistentContainer interfacing to a persistent store in a non-default location.

    The NSPersistentContainer exposes the defaultDirectoryURL, and states:

    This method returns a platform-dependent NSURL at which the persistent store(s) will be located or are currently located. This method can be overridden in a subclass of NSPersistentContainer.

    If you subclass NSPersistentContainer and define the defaultDirectoryURL to be an App Group directory using containerURLForSecurityApplicationGroupIdentifier, you should then be able to access the container between your application and extensions (assuming they have the same App Group entitlements).

    NSPersistentContainer also exposes persistentStoreDescriptions which also features a URL instance. Likewise, you may be able to update this to the App Group URL before calling loadPersistentStoresWithCompletionHandler:.

    Note that I have not used NSPersistentContainer, and have no idea whether this sharing would cause any concurrency issues.

提交回复
热议问题