swift2 Swift语法错误

4si2a6ki  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(180)

有人能帮我修复这些错误吗?Swift已经更改了,我不知道如何更改这些错误,使其与新版本兼容:
此错误会产生以下错误:
无法使用类型为(SwiftCoreDataHelper.Type,具有中间目录:)的参数列表调用createDirectoryAtPath布尔值,属性:NilLiteralConvertible,错误:输入输出NSError?)

NSFileManager.defaultManager().createDirectoryAtPath(SwiftCoreDataHelper, withIntermediateDirectories: true, attributes: nil, error: &error)

接下来的几个人就给我说明,“错误”是一个额外的参数:

if storeCoordicator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error){
        if (error != nil){
            print(error!.localizedDescription)
            abort()
        }
    }

let items: NSArray = managedObjectContext.executeFetchRequest(fetchRequest, error: nil)
9ceoxa92

9ceoxa921#

在Swift 2中,你需要捕获带有do-catch块的错误;将addPersistentStoreWithType与CoreData配合使用时,您需要执行以下操作:

do
{
    try storeCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
}
catch(let error as NSError)
{
    NSLog(error.localizedDescription) //error has occurred.
    abort() //abort
}

executeFetchRequest也是如此:

do
{
    let items: NSArray = try managedObjectContext.executeFetchRequest(fetchRequest)
}
catch(let error as NSError)
{
    NSLog(error.localizedDescription)
}

createDirectoryAtPath一样:

do
{
    try NSFileManager.defaultManager().createDirectoryAtPath(SwiftCoreDataHelper, withIntermediateDirectories: true, attributes: nil)
}
catch(let error as NSError)
{
    NSLog(error.localizedDescription)
}

相关问题