扩展UIAlertController方便初始化警告

ma1*_*w28 5 warnings initialization ios swift uialertcontroller

当我定义一个UIAlertController便利初始化器时:

extension UIAlertController {
    convenience init(message: String?) {
        self.init(title: nil, message: message, preferredStyle: .Alert)
        self.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
    }
}
Run Code Online (Sandbox Code Playgroud)

并在我的子类中的按钮操作中使用它UIViewController:

func buttonAction(button: UIButton) {
    let alert = UIAlertController(dictionary: nil, error: nil, handler: nil)
    presentViewController(alert, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

然后单击模拟器上的那个按钮,我收到一个警告:

尝试在取消分配时加载视图控制器的视图是不允许的,并且可能导致未定义的行为(UIAlertController)

但是,如果不使用便利初始化程序,我不会收到警告,我使用全局函数:

func UIAlertControllerWithDictionary(message: String?) -> UIAlertController {
    let alert = UIAlertController(title: nil, message: message, preferredStyle: .Alert)
    alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
    return alert
}
Run Code Online (Sandbox Code Playgroud)

我已将此报告给Apple作为iOS SDK错误.

在它修复之前,可以忽略警告并使用便利初始化程序吗?

flu*_*nic 9

我注意到便利初始化器存在同样的问题.它实际上是两个错误.

  1. Swift分配一个UIAlertController实例.
  2. Swift使用Swift创建的实例调用您的便利init.
  3. 你在那里调用UIKit的方便init,它实际上就是Objective-C工厂方法+(id) alertControllerWithTitle:message:preferredStyle:.
  4. 有UIKit分配自己的UIAlertController实例.(Bug#1)
  5. UIKit建立了自己的实例.
  6. UIKit释放你的Swift实例.
  7. UIAlertController's deinit(dealloc)访问view导致日志消息的属性.(Bug#2)
  8. Control返回到您自己的便利init,self从Swift的UIAlertController实例静默地更改为UIKit 的实例.
  9. 你现在所做的一切都发生在UIKit创建的实例上,这很好.

所以第一个错误是Swift创建了一个临时的UIAlertController,它被破坏而没有被使用过.

第二个错误是在取消初始化期间UIViewController访问view属性,它不应该访问.


关于你的问题:
两个错误都不应该有问题,所以我们现在可以简单地忽略这个警告.我也这样做,并没有任何问题 - 只是日志中的警告.