2013-05-31 32 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