2016-03-04 87 views
0

這感覺很奇怪,我無法通過搜索找到答案。請幫忙。這是Xcode iOS模擬器上的一個問題。模擬器應用程序之間SQLite數據丟失啓動

我正在寫一個數據持久性代碼。當實例化數據存儲時,我幾乎從Apple複製了以下代碼片段(https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html#//apple_ref/doc/uid/TP40001075-CH4-SW1)。

現在,問題似乎 - storeURL(在調試時)是一個包含長數字字符串的URL,並且在重新啓動模擬器時,該長數字字符串已更改。所以sqlite文件無法再被訪問。我相信我保存了正確的數據,因爲我通過代碼調試(和上下文保存api調用沒有錯誤),我保存後(沒有重新啓動)檢索數據,我看到數據使用命令行sqlite工具對sqlite文件。

請幫忙。謝謝!

import UIKit 
import CoreData 
class DataController: NSObject { 
    var managedObjectContext: NSManagedObjectContext 
    init() { 
     // This resource is the same name as your xcdatamodeld contained in your project. 
     guard let modelURL = NSBundle.mainBundle().URLForResource("DataModel", withExtension:"momd") else { 
      fatalError("Error loading model from bundle") 
     } 
     // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. 
     guard let mom = NSManagedObjectModel(contentsOfURL: modelURL) else { 
      fatalError("Error initializing mom from: \(modelURL)") 
     } 
     let psc = NSPersistentStoreCoordinator(managedObjectModel: mom) 
     self.managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) 
     self.managedObjectContext.persistentStoreCoordinator = psc 
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { 
      let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) 
      let docURL = urls[urls.endIndex-1] 
      /* The directory the application uses to store the Core Data store file. 
      This code uses a file named "DataModel.sqlite" in the application's documents directory. 
      */ 
      let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite") 
      do { 
       try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil) 
      } catch { 
       fatalError("Error migrating store: \(error)") 
      } 
     } 
    } 
} 
+0

而不是複製Mac代碼並嘗試在iOS上使用它,請執行以下操作:在創建iOS項目時,選中Core Data複選框。這可以提前給你正確的模板代碼。 – matt

+0

謝謝你馬特。是。這解決了這個問題。 –

+0

很酷。我想你可能在代碼中犯了一些錯誤,但我太懶惰,無法找到它。 :) – matt

回答

0

這是基本上馬特在評論部分說的。此問題與放置.sqlite文件的位置有關。

相關問題