切换存储文件 (翻译)

来源:互联网 发布:js 点击链接 编辑:程序博客网 时间:2024/06/13 05:31

原地址 http://nghialuong.com/blog/iOS-Switching-storage-files/

这里写图片描述

正如我们所知道的,Core Data是Cocoa的一个给力的框架,有了它我们可以很容易地在iOS app上做数据相关的操作。今天我打算对这个有趣主题写一些东西。

主题如下:
如果我们想要切换到物理存储地址,你可以设想一下用户想要使用少量帐号,所以我们必须针对每一个帐号存储每一个文件。这将会使得app加载更快,因为它将会在屏幕上显示已经加载的数据而且如果需要的话将会获取一些背景信息。

切换存储文件

这是我写的一个例子,很容易理解。除了主要的转移存储文件工作,还有关于如何使用NSFetchedResultsController 和 UITableView 。这是一个apple提供的很酷的特点。

以下是项目例子
https://github.com/nghialuong/StorageSwitching

回到主题,存储文件之间的转移只是一个例子,我们基本上把persistenstores 从 persistenstoreCoordinator中移除而且重新添加它。但是首先不要忘记去保存这种情形。

-(void)reloadStore {    // save state    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];    NSError *error = nil;    if (![context save:&error]) {        // Replace this implementation with code to handle the error appropriately.        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);        abort();    }    // remove all persistent stores    for (NSPersistentStore *store in _persistentStoreCoordinator.persistentStores) {        [_persistentStoreCoordinator removePersistentStore:store error:nil];    }    // add new persistent store with specified storage location    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:[self storageName];    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType                                                   configuration:nil                                                             URL:storeURL                                                         options:[self storeOptions]                                                           error:nil]) {        NSLog(@"Can not add Persistent store.");        return;    }}

更近一步说,我想提供一个能用的链接 http://corsarus.com/2015/core-data-for-ios-part-1-data-model/ ,通过它可以对 Core Data 有更全面的理解。这个系列很容易理解,希望我们能从中有所收获。

Migration:
除了这个,apple提供很酷的特征 Migration ,我们可以在存储位置和数据类型间转移。更多细节,可以阅读这个 https://www.objc.io/issues/10-syncing-data/icloud-core-data/#icloud_on__off_switch

但是请注意,这个不是switching,这个是新旧的合并,所以在这两之间操作的时候小心一点。

最后,如果我的项目对你有好处,不要犹豫给我star吧,哈哈。

0 0