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)")
}
}
}
}
而不是复制Mac代码并尝试在iOS上使用它,请执行以下操作:在创建iOS项目时,选中Core Data复选框。这可以提前给你正确的模板代码。 – matt
谢谢你马特。是。这解决了这个问题。 –
很酷。我想你可能在代码中犯了一些错误,但我太懒惰,无法找到它。 :) – matt