核心数据迁移问题:storePath无法启动
core data migration issue: storePath cannot be initiated
我尝试将一些核心数据代码从swift2迁移到swift4。代码如下:
/// Removes the existing model store specfied by the receiver.
///
/// - returns: A tuple value containing a boolean to indicate success and an error object if an error occurred.
public func removeExistingModelStore() -> (success: Bool, error: NSError?) {
var error: NSError?
let fileManager = FileManager.default
if let storePath = storeURL.path {
if fileManager.fileExists(atPath: storePath) {
let success: Bool
do {
try fileManager.removeItem(at: storeURL)
success = true
} catch let error1 as NSError {
error = error1
success = false
}
if !success {
print("*** \(String(describing: CoreDataModel.self)) ERROR: [\(#line)] \(#function) Could not remove model store at url: \(String(describing: error))")
}
return (success, error)
}
}
return (false, nil)
}
构建错误显示 "Initializer for conditional binding must have Optional type, not 'String'"。所以我用谷歌搜索并遵循了删除可选绑定的建议:
let storePath = storeURL.path { ... }
然后在上面的地方又出现了两个新的错误:1. 不能调用非函数类型的值'String'; 2.变量在其自身初始值范围内使用
我相信上面的代码主要是 setup/teardown 核心数据模型的样板代码。我是初学者所以请帮助!
如果你从if let
中删除了if
,那么你也必须删除{ }
,你可以试试
public func removeExistingModelStore() -> (success: Bool, error: Error?) {
if FileManager.default.fileExists(atPath: storeURL.path ) {
do {
try FileManager.default.removeItem(at: storeURL)
return (true, nil)
} catch {
return (false, error)
}
}
return (false, nil)
}
我尝试将一些核心数据代码从swift2迁移到swift4。代码如下:
/// Removes the existing model store specfied by the receiver.
///
/// - returns: A tuple value containing a boolean to indicate success and an error object if an error occurred.
public func removeExistingModelStore() -> (success: Bool, error: NSError?) {
var error: NSError?
let fileManager = FileManager.default
if let storePath = storeURL.path {
if fileManager.fileExists(atPath: storePath) {
let success: Bool
do {
try fileManager.removeItem(at: storeURL)
success = true
} catch let error1 as NSError {
error = error1
success = false
}
if !success {
print("*** \(String(describing: CoreDataModel.self)) ERROR: [\(#line)] \(#function) Could not remove model store at url: \(String(describing: error))")
}
return (success, error)
}
}
return (false, nil)
}
构建错误显示 "Initializer for conditional binding must have Optional type, not 'String'"。所以我用谷歌搜索并遵循了删除可选绑定的建议:
let storePath = storeURL.path { ... }
然后在上面的地方又出现了两个新的错误:1. 不能调用非函数类型的值'String'; 2.变量在其自身初始值范围内使用
我相信上面的代码主要是 setup/teardown 核心数据模型的样板代码。我是初学者所以请帮助!
如果你从if let
中删除了if
,那么你也必须删除{ }
,你可以试试
public func removeExistingModelStore() -> (success: Bool, error: Error?) {
if FileManager.default.fileExists(atPath: storeURL.path ) {
do {
try FileManager.default.removeItem(at: storeURL)
return (true, nil)
} catch {
return (false, error)
}
}
return (false, nil)
}