0

我基本上是试图通过引入一个 sqlite 数据库而不是每次都下载数据来提高我的应用程序的效率。我没有包含带有预填充信息的默认 sqlite 文件,我希望应用程序下载一次,其想法是用户可以选择何时更新。

现在我相信我已经有了 sqlite 数据库,我已经在模拟器中检查了它,并且数据已经下载并正确映射。在我看来,我正在做一个 getObjectsAtPath。我想要做的是告诉应用程序使用我已经在 sqlite 数据库中获得的内容,而不是重新下载相同的数据。

在我的 AppDelegate.m 我做了

NSString *path = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"Blogs.sqlite"];
// I added the following line in an attempt to get the app to use the sqlite file already created
NSString *seedPath = [[NSBundle mainBundle] pathForResource:@"Blogs" ofType:@"sqlite"];
NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:path fromSeedDatabaseAtPath:seedPath withConfiguration:nil options:nil error:&error];

[managedObjectStore createManagedObjectContexts];

// Set the default store shared instance
[RKManagedObjectStore setDefaultStore:managedObjectStore];

// Configure a managed object cache to ensure we do not create duplicate objects
managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectStore.persistentStoreManagedObjectContext];

在我的 ViewController 我有

[[RKObjectManager sharedManager] getObjectsAtPath:@"/post" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
    // Do stuff with fetchedResultsController
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    // Show some errors
}];

- (NSFetchedResultsController *)fetchedResultsController
{
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Post"     inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];


[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"post_title" ascending:YES];
NSArray *sortDescriptors = @[sortDescriptor];    
[fetchRequest setSortDescriptors:sortDescriptors];

// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Location"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;

return _fetchedResultsController;

}

如果有任何更相关的代码我应该发布或更详细的信息,我可以添加到问题中,请询问。谢谢阅读。

4

1 回答 1

0

采取不同的方法。将您的视图控制器从获取新数据中抽象出来(除了托管用户用来触发获取新数据的按钮)。相反,让视图控制器观察 MOC 以获取他们的数据并在数据更改时更新 UI(FRC 很方便 - NSFetchedResultsController)。

RestKit 不是基于尝试猜测您想要本地结果还是远程结果。当你告诉它你想要它们时,它会得到远程结果,映射它们并存储它们以供你在本地使用。

现在,您可以在首次加载应用程序时(安装后)触发数据请求。之后,您仅在用户点击按钮刷新时才发出请求。在任何一种情况下,您的视图控制器都只是观察 MOC 并显示到达的任何新数据。

于 2013-10-13T12:43:05.303 回答