1

こんにちは、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() 関数を実行するかについて混乱しています

何かアイデア〜?どうもありがとう

4

2 に答える 2

1

do {}にあるものはすべて善であり、内にあるものはすべてcatch {}悪である

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

エラー処理または abort() ステートメントのいずれかを使用します

于 2015-10-02T15:44:54.200 に答える
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()
}
于 2015-10-02T15:34:25.413 に答える