什么是Swift 4的良好实践'错误处理'?

时间:2018-04-30 19:11:37

标签: swift xcode core-data error-handling swift4

请有人指导我使用'错误处理'方法和我下面的'工作'(Swift 4)代码进行良好练习...(例如:'Guards','Do','Catch',Throw', 'if','else')...

//// Import //// import UIKit import CoreData

//// Custom Function //// func insertCoreData(){ if let coreData = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext { let data = MyEntity(entity: MyEntity.entity(), insertInto: coreData) data.name = "Joe Blogs" data.country = "United Kingdom" try? coreData.save() print("Data Saved...") } }

//// Output Function /// insertCoreData() // Working and Gives

2 个答案:

答案 0 :(得分:0)

如果你打算使用“try?”进行错误处理,那么你会遇到很多麻烦,尤其是在保存数据这样的情况下。

请大家帮忙并使用正确的do / try / catch(或重新投掷)作为处理错误的标准方法并仅使用try?或者尝试!在你意识到后果的非常具体的情况下。这是更多的代码编写,但只要你遇到某种问题,你就会感激额外的努力。

do {
  try coreData.save()
} catch {
  print("Unable to save Managed Object Context")
  print("\(error), \(error.localizedDescription)")
}

答案 1 :(得分:0)

Do,Try,Catch是一个很好的开始,它是Xcode在CoreData安装过程中为您加载的默认实现。

同时,它建议您为应用程序实施正确的错误处理。以下是一些原因。默认情况下,它只会输出错误信息。

   /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */

Sean Allen有一个关于Do,Try Catch的好视频,展示了如何处理错误的示例。看看这个。 youtube - do, try, catch

相关问题