我正在处理iOS项目,我注意到一件事,就是每当我需要显示错误时,我会一次又一次地创建一个警报框。我想重构代码以消除冗余。我的问题是:对于这个特定的场景,创建一个错误处理类是重构的正确方法吗?例如,我将创建以下类
class ErrorHandler {
func ShowAlertBox(Title: String, Message: String, ViewController: UIViewController) {
let alertController = UIAlertController(title: Title, message: Message), preferredStyle: .Alert)
let doneAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label to cancel sign-in failure."), style: .Cancel, handler: nil)
alertController.addAction(doneAction)
ViewController.presentViewController(alertController, animated: true, completion: nil)
}
}
像这样打电话:
instanceofErrorHandler.ShowAlertBox("Error","Log In Error", SignInViewController)
最佳答案
我怀疑对于如何处理这种情况有很多不同的意见,我认为你的方法没有任何问题。也就是说,我的方法是创建一个名为ViewControllerUtilities
的扩展,并将所有的公共函数放在其中:
protocol ViewControllerUtilities {}
extension ViewControllerUtilities where Self: UIViewController {
func showAlert(_ title: String = "Error", message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
仅供参考,我也有功能在那里,以检查网络是否可以访问。然后,只需将
ViewControllerUtilities
添加到视图控制器所遵循的协议列表中,就可以获得所有这些功能:class MyViewController: UIViewController, ViewControllerUtilities {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
showAlert("Error", message: "Sorry, had an error.")
}
}