我正在开发iOS项目,我注意到的一件事是,每当我需要显示错误时,我会一次又一次地创建一个警告框。我想重构该代码以消除冗余。我的问题是:创建一个错误处理类是为这个特定场景重构的正确方法吗?例如,我会创建一个以下的类
bool awaitingPlayingPieceSelection = false;
void Update () {
if (chance == 1) {
if (Input.GetKeyUp (KeyCode.Space)) {
if (enableInput == true) {
enableInput = false;
markers [0].gameObject.SetActive (true);
markers [1].gameObject.SetActive (false);
markers [2].gameObject.SetActive (false);
markers [3].gameObject.SetActive (false);
a.PlayOneShot (s_Dice);
DiceRoll ();
if (subPlayer == 4 && diceno == 6) {
// ...
} else if (subPlayer == 3 && diceno == 6) {
awaitingPlayingPieceSelection = true;
}
}
}
}
if (awaitingPlayingPieceSelection) {
if (Input.GetMouseButtonDown(0)) {
// Perform your raycast in here for piece selection
// Only set the variable to false once the player has selected a valid piece
// If they click something else, keep waiting for input
awaitingPlayingPieceSelection = false;
}
}
}
并且这样打电话:
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)
}
}
答案 0 :(得分:1)
我怀疑在如何处理这种情况方面存在很多不同的意见,我不认为你的方法存在任何问题。也就是说,我这样做的方法是创建一个名为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.")
}
}