模拟器应用程序之间的SQLite数据丢失

时间:2016-03-04 00:37:59

标签: ios iphone swift ios-simulator xcode7

这感觉很奇怪,我通过搜索无法找到答案。这是Xcode iOS模拟器上的一个问题。

我正在写一个数据持久性代码。在实例化数据存储时,我几乎从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文件。< / p>

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)")
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这就是Matt在评论部分所说的基本内容。此问题与放置.sqlite文件的位置有关。