持久的数据存储迅速

时间:2015-11-05 15:53:55

标签: ios swift sqlite persistent

我目前正在开发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,   错误:&错误)

重新启动应用程序时,

始终为空。

你有什么想法吗?

0 个答案:

没有答案