2013-05-31 35 views
2

我在从RestKit世界中的CoreData获取数据时遇到了一些问题。我能够成功地将JSON数据从服务器映射到我的NSManagedObject实体。但我不知道如何获取RestKit存储在本地存储中的数据。使用RestKit从CoreData获取本地数据0.2

我尝试使用下面的代码来从本地存储中获取数据:

NSManagedObjectContext* context = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext; 
// NSManagedObjectContext* context = [[[RKObjectManager sharedManager] managedObjectStore] mainQueueManagedObjectContext]; 
    NSError *error = nil; 
    NSEntityDescription *entityDescription = [NSEntityDescription 
              entityForName:@"DTUser" inManagedObjectContext: context]; 
    NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
    [request setEntity:entityDescription]; 
    NSArray *dtContents = [context executeFetchRequest:request error:&error]; 
    NSLog(@"Content :%@", dtContents); 

但它返回一个空数组。

+0

应该加载什么以及何时运行该代码?你有没有设置defaultStore? – Wain

+0

@ Wain:是的,我设置了默认商店。我能够将JSON数据正确映射到我的核心数据实体。并且在映射后,当我做 int count = [context countForEntityForName:@“MyEntity”谓词:nil error:nil]; 它给了我正确的实体数量。但是,一旦我关闭(终止)应用程序,并再次打开应用程序,并再次执行下面的代码: int count = [context countForEntityForName:@“MyEntity”predicate:nil error:nil]; 它将计数返回为零。 – tek3

+0

你已经调试过,检查你是否有一个有效的上下文,并检查了获取请求错误?你如何创建核心数据栈? – Wain

回答

2

使用addInMemoryPersistentStore:不保存到磁盘,所以当应用程序关闭时,所有数据都消失了。改用addSQLitePersistentStoreAtPath:来代替。

+0

感谢您的回复。 – tek3