尝试抓住swift 2

时间:2015-10-02 15:27:29

标签: swift2 do-catch

对于如何将if_else错误处理转移到try catch成功,我有点困惑。

这是我的代码。

let error : NSError?
if(managedObjectContext!.save()) {
    NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)    
    if error != nil {
       print(error?.localizedDescription)
    }
}
else {
    print("abort")
    abort()
}

现在我像这样转换为swift 2.0

do {
   try managedObjectContext!.save()
}
catch {
     NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
     print((error as NSError).localizedDescription)
}

我对打印中止的位置和执行abort()函数感到困惑

任何想法〜?非常感谢

2 个答案:

答案 0 :(得分:1)

重写代码以使其与原始代码相同

do {
   try managedObjectContext!.save()

   //this happens when save did pass
   NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)    

   //this error variable has nothing to do with save in your original code
   if error != nil {
       print(error?.localizedDescription)
   }
}
catch {
   //this happens when save() doesn't pass
   abort()
}

您可能想要写的内容如下:

do {
   try managedObjectContext!.save()

   //this happens when save did pass
   NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)    
}
catch let saveError as NSError {
   //this happens when save() doesn't pass
   print(saveError.localizedDescription)
   abort()
}

答案 1 :(得分:1)

do {}内的所有内容都很好,catch {}内的所有内容都不好

do {
   try managedObjectContext!.save()
   NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
}
catch let error as NSError {
     print(error.localizedDescription)
     abort()
}

使用错误处理或abort()语句

相关问题