一尘不染

Swift 2:通话可能引发,但未标记为“ try”且未处理错误

swift

在安装Xcode 7 Beta并将Swift代码转换为Swift 2之后,我遇到了一些我无法弄清楚的代码问题。我知道Swift
2是新手,所以我搜索并找出了答案,因为没有任何相关内容,我应该写一个问题。

这是错误:

可以抛出呼叫,但未将其标记为“ try”,并且未处理错误

码:

func deleteAccountDetail(){
        let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
        let request = NSFetchRequest()
        request.entity = entityDescription

        //The Line Below is where i expect the error
        let fetchedEntities = self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
        }

        do {
            try self.Context!.save()
        } catch _ {
        }

    }

快照: 在此处输入图片说明


阅读 192

收藏
2020-07-07

共1个答案

一尘不染

您必须像save()处理呼叫一样捕获错误,并且由于您要在此处处理多个错误,因此可以try在一个do-catch块中依次进行多个调用,如下所示:

func deleteAccountDetail() {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
            self.Context!.deleteObject(entity)
        }

        try self.Context!.save()
    } catch {
        print(error)
    }
}

或如@
bames53在下面的注释中指出的,通常最好的做法是不要在引发错误的地方捕获错误。您可以将方法标记为,throws然后try调用该方法。例如:

func deleteAccountDetail() throws {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()

    request.entity = entityDescription

    let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]

    for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
    }

    try self.Context!.save()
}
2020-07-07