gpt4 book ai didi

ios - 扩展 UIAlertController 便利初始化警告

转载 作者:搜寻专家 更新时间:2023-10-30 22:28:33 24 4
gpt4 key购买 nike

当我定义一个UIAlertController convenience initializer时:

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, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
return alert
}

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

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

最佳答案

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

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

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

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


关于您的问题:
这两个错误应该都不是问题,所以我们现在可以简单地忽略警告。我也这么做了,目前还没有任何问题 - 只是日志中的那个警告。

关于ios - 扩展 UIAlertController 便利初始化警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33805197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com