Swift,为什么这个本地变量没有被释放?

标签 swift automatic-ref-counting rx-swift

我在 awakeFromNib 函数中创建了一个局部变量,在 UIView 动画 block 中使用它,但它从未被释放,为什么?

这是代码(在 UITableViewCell 的 awakeFromNib 中)

var fullPhotoDisposeBag = DisposeBag()
fullScreenImageView.rx.tapGesture().when(UIGestureRecognizerState.recognized).subscribe(onNext: { (tap) in

      UIView.animate(withDuration: 0.15, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
            fullScreenImageView.frame = oldFullScreenFrame
      }, completion: { (finished) in
           fullScreenImageView.removeFromSuperview()
           let _ = fullPhotoDisposeBag //This line avoid early release, but retains too much...
      })
}, onDisposed:{
       print("disposed")
}).addDisposableTo(fullPhotoDisposeBag)

一个线索是 tableView 位于我的应用程序的一个选项卡的根目录下,因此 UITableView 永远不会被释放,因此 UITableViewCell 由于可重用性而永远不会被释放。 但是为什么 ARC 会保留这个变量呢?仅在函数和完成 block 中使用?

PS:我目前使用一个可选的 DisposeBag,我在完成 block 中设置为 nil,但我不明白为什么我需要这样做......

最佳答案

看起来像一个保留循环。我的猜测是垃圾收集器在完成闭包停止引用它之前不会释放局部变量,并且完成闭包永远不会释放,因为它由您的本地函数拥有。

我的建议是将此代码从您的 UIView 移至您的 UIViewController,因为应该在此处定义此类行为。

关于Swift,为什么这个本地变量没有被释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46860265/

相关文章:

ios - 从后台返回后崩溃

ios - ReactiveX,关于移动应用架构和层

ios - 当我使用约束时 AVMakeRect 返回工作值

ios - ARC - popviewController/DismissViewController

swift - R.swift 命令 PhaseScriptExecution 失败,退出代码为非零

objective-c - 关于 ARC for iOS 的几个问题?

rx-swift - Swift Combine 中 BehaviorRelay 的替代方案

swift - RxSwift 中多节表格 View 的 ViewModel 输入和输出

ios - NSURLErrorDomain 中的代码是什么意思?

Swift 4 iMessage 发送消息 : The operation couldn’t be completed.(com.apple.messages.messagesapp-error 错误 9。)