2013-07-23 103 views
5

我读过一些关于NSIncrementalStore的文章,我仍然对整个概念感到困惑。在这个post我们可以读到:NSIncrementalStore - 使用本地和远程数据

从本质上讲,你现在可以创建NSPersistentStore自定义子类, 让,而不是你的NSFetchRequest创下了本地SQLite 数据库,它运行你定义可以做一些随心所欲的方法 返回结果(如发出网络请求)。

到现在为止我还以为NSIncrementalStore是访问远程数据和保存/缓存在本地一个完美的解决方案。现在,我推断这只是用于访问远程数据的解决方案。

如果我是对的,我会很感激任何关于某些解决方案的建议。 如果我错了,魔法在哪里以及如何实施?关于NSIncrementalStore的每篇文章/文章/教程展示了从服务器拉取数据是多么容易,但他们都没有提供关于缓存事物以供脱机查看的一条线索。

回答时,让我们考虑一个常见的情况,即应用程序应该从Internet下载一些数据,并在本地显示并保存,以便用户可以脱机使用该应用程序。

此外,我不承诺使用NSIncrementalStore或其他东西。我只是在寻找最好的解决方案,而这个课程被这个领域的一些最好的专家描述为一个。

回答

0

我也困惑了大约4或5小时:) 所以。 您继承的NSPersistentStore类是远程数据存储的“表示”。

所以,对于访问远程数据和保存/缓存在本地你需要做以下

1)创建NSPersistentStore和设置它的子类。

就像是:

YOURIncrementalStore *incrementalStore = [coordinator addPersistentStoreWithType:[YOURIncrementalStore type] configuration:nil URL:nil options:nil error:&error];

地方协调你的主要NSPersistentStoreCoordinator

2)然后,你需要其他NSPersistentStoreCoordinator,将 “协调地方代表(incrementalStore)和上下文外部存储的”并提供本地存储代表(如SQLite DB URL):

[incrementalStore.backingPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]

但不要忘记,你的新持久性商店必须知道你所有的以前的当地的状态。所以选项字典将是:

NSDictionary *options = @{ NSInferMappingModelAutomaticallyOption : @YES, NSMigratePersistentStoresAutomaticallyOption:@YES }

那么,恕我直言,我明白所有的内部工作是这样的:

您向外部API的一些数据。解析它,然后保存到backingPersistentStoreCoordinator的上下文中,然后合并到主要的一个。所以所有情境的状态将是平等的。

以前的所有文本均基于使用AFIncrementalStore解决方法。

我的代码与MagicalRecord实施AFIncrementalStore:正确

- (void)addMRAndAFIS { 
    [MagicalRecord setupCoreDataStack]; 

    NSURL *storeURL = [NSPersistentStore urlForStoreName:[MagicalRecord defaultStoreName]]; 
    NSPersistentStoreCoordinator *coordinator = [NSPersistentStoreCoordinator defaultStoreCoordinator]; 
    NSError *error = nil; 
    NSArray *arr = coordinator.persistentStores; 
    AFIncrementalStore *incrementalStore = (AFIncrementalStore*)[coordinator addPersistentStoreWithType:[PTIncrementalStore type] configuration:nil URL:nil options:nil error:&error]; 

    NSDictionary *options = @{ NSInferMappingModelAutomaticallyOption : @YES, 
         NSMigratePersistentStoresAutomaticallyOption:@YES }; 
    arr = coordinator.persistentStores; 
    if (![incrementalStore.backingPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) { 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    } 
    } 

如果我们需要讨论的最简单的方法,你只需要继承NSIncrementalStore,设置它(像我写的),解析数据,然后创建一些上下文,保存日期,然后保存并合并到父上下文。

因此,您将拥有2个商店和2个上下文以及1个StoreCoordinator。

如果我在某处犯了错误,请参考它。

也试试:https://gist.github.com/stevederico/5316737

+0

我已经开始实现我自己的子类。我将尽快公开发布,敬请关注。 :D – wczekalski

+1

那又如何?你得到你想要的东西吗? –

+0

我仍然在做,但我很快就会完成。它会在我的github上可用 - github.com/wczekalski – wczekalski

相关问题