在 UIAlertController SubClass Dismiss 之前未调用自定义委托函数
Custom Delegate function not called befor UIAlertController SubClass Dismiss
我创建了一个 UIAlertController 的子类,它做了一些事情,但在取消它之前,我调用了 Delegate(是委托模式的自定义协议,在 UIViewController 中使用它),就在 dimiss 语句之前
- 在我的自定义警报中插入此代码 Class。
- 我在 UIViewController 中有一个强大的引用,并将委托设置为 self。
- 遵守协议并设置运行时从未到达的断点。
// this code in my custom subClass of UIAlertController
func addRequestAction() {
addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak self] _ in
self?.checkConnection { isConnected in
print("xxxxxxxxx", isConnected)
DispatchQueue.main.async {
if isConnected {
self?.delegate?.didConnect() // here i call delegate function but never executed
self?.dismiss(animated: true, completion: nil)
} else {
let alert = NetworkCheckerAlert(self?.delegate)
self?.dismiss(animated: true, completion:nil)
guard let viewController = UIApplication.shared.keyWindow?.rootViewController else { return }
viewController.present(alert, animated: true, completion: nil)
}
}
}
}))
}
删除 [weak self]
应该可以解决问题:
addAction(UIAlertAction(title: "OK", style: .default, handler: { /*[weak self]*/ _ in
通常在视图控制器中,使用 [weak self]
没问题,因为 self
指的是 VC,但这里的 self
指的是 UIAlertController
.
我假设您在呈现自定义警报控制器时没有保留对它的引用(即您只是将其声明为局部变量,呈现它,然后将其丢弃)。
现在让我们考虑当 DispatchQueue
闭包为 运行 时会发生什么。此时,警报已经被解除,所以“屏幕”没有保留对它的引用。由于没有任何东西保留对警报控制器的强引用(仅存在来自闭包的弱引用),UIAlertController
子类的实例被释放。
虽然这只是一个猜测。您可以使用描述的方法 (由我编写)查看哪些对象在内存中,以及谁持有对谁的引用,从而进行更多调查。
我创建了一个 UIAlertController 的子类,它做了一些事情,但在取消它之前,我调用了 Delegate(是委托模式的自定义协议,在 UIViewController 中使用它),就在 dimiss 语句之前
- 在我的自定义警报中插入此代码 Class。
- 我在 UIViewController 中有一个强大的引用,并将委托设置为 self。
- 遵守协议并设置运行时从未到达的断点。
// this code in my custom subClass of UIAlertController
func addRequestAction() {
addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak self] _ in
self?.checkConnection { isConnected in
print("xxxxxxxxx", isConnected)
DispatchQueue.main.async {
if isConnected {
self?.delegate?.didConnect() // here i call delegate function but never executed
self?.dismiss(animated: true, completion: nil)
} else {
let alert = NetworkCheckerAlert(self?.delegate)
self?.dismiss(animated: true, completion:nil)
guard let viewController = UIApplication.shared.keyWindow?.rootViewController else { return }
viewController.present(alert, animated: true, completion: nil)
}
}
}
}))
}
删除 [weak self]
应该可以解决问题:
addAction(UIAlertAction(title: "OK", style: .default, handler: { /*[weak self]*/ _ in
通常在视图控制器中,使用 [weak self]
没问题,因为 self
指的是 VC,但这里的 self
指的是 UIAlertController
.
我假设您在呈现自定义警报控制器时没有保留对它的引用(即您只是将其声明为局部变量,呈现它,然后将其丢弃)。
现在让我们考虑当 DispatchQueue
闭包为 运行 时会发生什么。此时,警报已经被解除,所以“屏幕”没有保留对它的引用。由于没有任何东西保留对警报控制器的强引用(仅存在来自闭包的弱引用),UIAlertController
子类的实例被释放。
虽然这只是一个猜测。您可以使用描述的方法