2017-03-13 161 views
2

我有一个实用程序类,其中包含多个其他类使用的函数。其中之一是一个报警功能:默认情况下使用调用对象的“self”的方法

class Utils { 
    func doAlert (title: String, message: String, target: UIViewController) { 
     let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) 
     alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil)) 
     target.present(alert, animated: true, completion: nil) 
    } 
} 

此功能将始终瞄准视图控制器上self,所以我想不用我每次调用该函数时添加target: self,但我不能只将其设置为默认值,因为这会导致它回到Utils类。有什么方法可以重写这个以避免这种情况?

回答

4

实用程序类是这个原因的反模式完全是,你真的想使用什么是extension

extension UIViewController { 
    func doAlert(title: String, message: String) { 
     let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) 
     alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil)) 
     self.present(alert, animated: true, completion: nil) 
    } 
} 

,然后就可以直接调用该方法上所有的控制器:

self.doAlert(title: "title", message: "message") 

通常避免使用实用方法的类。尝试将方法添加到功能实际所属的类型中。

2

而不是把功能在你的Utils类的,你可以把它放在一个扩展的UIViewController,像这样:

extension UIViewController { 
     func doAlert (title: String, message: String) { 
      let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) 
      alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil)) 
      target.present(alert, animated: true, completion: nil) 
     } 
相关问题