ios – 扩展UIAlertController方便初始化警告

前端之家收集整理的这篇文章主要介绍了ios – 扩展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))
    }
}

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

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

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

Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (UIAlertController)

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

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

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

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

解决方法

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

> Swift分配一个UIAlertController实例.
> Swift使用Swift创建的实例调用您的便利init.
>你在那里调用UIKit的方便init,它实际上是Objective-C工厂方法(id)alertControllerWithTitle:message:preferredStyle:.
> UIKit会分配自己的UIAlertController实例. (Bug#1)
> UIKit设置自己的实例.
> UIKit释放你的Swift实例.
> UIAlertController的deinit(dealloc)访问view属性,该属性导致日志消息. (Bug#2)
> Control返回到您自己的便利init,其中自我静默地从Swift的UIAlertController实例更改为来自UIKit的实例.
>你现在所做的一切都发生在UIKit创建的实例上,这很好.

所以第一个错误是Swift创建了一个临时的UIAlertController,它在没有被使用的情况下被销毁.

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

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

原文链接:https://www.f2er.com/iOS/330586.html

猜你在找的iOS相关文章