我基本上試圖通過引入一個SQLite數據庫,而不是每次下載數據,以提高我的應用程序的效率。我沒有包含預填充信息的默認sqlite文件,我希望應用程序下載一次,其想法是用戶可以選擇何時更新。獲取Restkit使用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;
}
如果有任何更多的相關代碼,我應該張貼或更詳細的,我可以添加到問題請詢問。謝謝閱讀。
我最終抽象了建議的數據檢索。對於未來的人們在這個問題上磕磕絆絆,NSNotifications在檢索數據時會有訣竅。然後視圖控制器使用NSFetchedResultsController顯示數據。乾杯。 – Rayzor