将核心数据保存到自己在 LibraryDirectory 中创建的目录时崩溃
core data crashed when save it to a directory created by myself in LibraryDirectory
这是我的代码,return 一个用于保存核心数据文件的目录。
lazy var applicationDocumentsDirectory: NSString = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.triplec.WKCC" in the application's documents Application Support directory.
var libP = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, true).first! as NSString
let path = libP.stringByAppendingPathComponent("coredata") as String
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(path) {
do {
try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
} catch { }
}
print(path)
return path as NSString
}()
当我调用下面的函数时,它崩溃了。
崩溃日志显示无法保存文件。
let url = NSURL.fileURLWithPath(self.applicationDocumentsDirectory.stringByAppendingPathComponent("SingleViewCoreData.sqlite"))
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
abort()
}
当我没有将字符串附加到 libP 时,它确实起作用了。
有谁知道如何将核心数据文件保存到自己创建的目录中吗?
您甚至还没有测试应该创建目录的代码以查看其是否有效。此代码:
if fileManager.fileExistsAtPath(path) {
do {
try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
} catch { }
}
...表示如果目录 已经存在 则创建它。但如果该目录不存在,则什么也不做。
这是我的代码,return 一个用于保存核心数据文件的目录。
lazy var applicationDocumentsDirectory: NSString = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.triplec.WKCC" in the application's documents Application Support directory.
var libP = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, true).first! as NSString
let path = libP.stringByAppendingPathComponent("coredata") as String
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(path) {
do {
try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
} catch { }
}
print(path)
return path as NSString
}()
当我调用下面的函数时,它崩溃了。
崩溃日志显示无法保存文件。
let url = NSURL.fileURLWithPath(self.applicationDocumentsDirectory.stringByAppendingPathComponent("SingleViewCoreData.sqlite"))
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
abort()
}
当我没有将字符串附加到 libP 时,它确实起作用了。
有谁知道如何将核心数据文件保存到自己创建的目录中吗?
您甚至还没有测试应该创建目录的代码以查看其是否有效。此代码:
if fileManager.fileExistsAtPath(path) {
do {
try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
} catch { }
}
...表示如果目录 已经存在 则创建它。但如果该目录不存在,则什么也不做。