Save In-Memory store to a file on iOS

喜欢而已 提交于 2019-12-12 09:24:08

问题


Let's say I already setup a in-memory core data store using this:

- (NSPersistentStore *)addPersistentStoreWithType:(NSString *)storeType configuration:(NSString *)configuration URL:(NSURL *)storeURL options:(NSDictionary *)options error:(NSError **)error;

and saved a lot of things to it.

Now I want to save all of this store into a file.

Is that possible?

I tried many kind of search but it looked like no one has ever bumped into this issue before.


回答1:


There's no way to just save the in-memory NSPersistentStore to a file. It doesn't conform to NSCoding or provide any methods of its own that would enable this, and the only way to ask it for its data is the usual Core Data approach of fetching it.

However, you can migrate to a file-based store pretty easily. Use your persistent store coordinator to migrate the memory-based store to a file. First make sure that you don't have any objects that still make use of the memory-resident store (NSManagedObjectContext, NSManagedObject). Then do something like:

NSURL *fileURL = // set this up to have the URL of the file you want
NSError *error = nil;
NSPersistentStore *fileStore = [self.persistentStoreCoordinator
    migratePersistentStore:self.memoryResidentStore
    toURL:fileURL
    options:nil
    withType:NSSQLiteStoreType
    error:&error];

Once you do this, the old persistent store (self.memoryResidentStore in the code above) is no longer useful.



来源:https://stackoverflow.com/questions/25015277/save-in-memory-store-to-a-file-on-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!