我目前正在开发iOS应用。我在NSManageObjectContext中保存了一些数据。在当前会话期间,数据可在模型中访问,但是当我重新启动时,应用程序数据不再存在。
在我的AppDelegate.swift中:
private lazy var _managedObjectModel: NSManagedObjectModel? = {
if let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd") {
return NSManagedObjectModel(contentsOfURL: modelURL)
} else {
return nil
}
}()
private lazy var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
if let managedObjectModel = self._managedObjectModel {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
if let url = self._applicationDocumentsDirectory?.URLByAppendingPathComponent("my.sqlite") {
var error: NSError?
coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error)
if let error = error {
ErrorManager.defaultManager().showFatalError(title: "Error: Core Data", message: Constants.LocalizedDownloadItAgain)
} else {
return coordinator
}
}
}
return nil
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
let managedObjectContext = NSManagedObjectContext()
if let coordinator = self._persistentStoreCoordinator {
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
} else {
return nil
}
}()
当我存储数据时,在我的CustomClass中:
private init() {
var error: NSError?
let request = NSFetchRequest(entityName: "BackingTracks")
request.sortDescriptors = [NSSortDescriptor(key: "position", ascending: true)]
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
if let managedObjectContext = appDelegate.managedObjectContext {
if let backingTracks = managedObjectContext.executeFetchRequest(request, error: &error) as? [BackingTrack] {
if error == nil {
if backingTracks.count == 0 {
let object = NSEntityDescription.insertNewObjectForEntityForName("BackingTracks", inManagedObjectContext: managedObjectContext) as? BackingTrack
object?.name = "test"
object?.code = "test"
object?.data = nil
}
} else {
ErrorManager.defaultManager().showFatalError(title: "Error: Core Data", message: error!.localizedFailureReason)
}
}
}
}
}
但变量backingTracks
重新启动应用程序时,backingTracks = managedObjectContext.executeFetchRequest(request, 错误:&错误)
始终为空。
你有什么想法吗?