swift(5)RxSwift之内存管理之一:普通使用

2019-08-10  本文已影响0人  __拼搏__
我们做开发的都知道,内存管理极为重要,创建的内存如果不能及时释放,积累到一定程度就会让程序崩溃。RxSwift作为优秀的开源框架对于内存管理自然也是极为严格。接下来,我们探究一下普通使用的时候,什么情况下会导致RxSwift的内存泄露。

Rx对于内存管理提供了一套非常方便的检测机制,只需要在pod里的tag的end之后里引入如下代码,并pod update

post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == 'RxSwift'
      target.build_configurations.each do |config|
        if config.name == 'Debug'
          config.build_settings['OTHER_SWIFT_FLAGS'] ||= ['-D', 'TRACE_RESOURCES']
        end
      end
    end
  end
end
接下来我们设计如下场景 image.png

我们在vc1里统计引用计数,在vc2里执行订阅操作。当我们订阅执行了之后,pop到vc1,观察引用计数的变化。核心代码如下:

我们在vc1里加入如下代码:

 override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("*****vc1即将出现,此时引用计数为: \(RxSwift.Resources.total)")
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        print("*****vc1已经消失,此时引用计数为: \(RxSwift.Resources.total)")
  
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("*****vc1的push即将执行,此时引用计数为: \(RxSwift.Resources.total)")
        let vc = vc2()
        self.navigationController?.pushViewController(vc, animated: true)
    }
操作一

首先在vc2的viewDidLoad里执行如下操作

 Observable<Any>.create {(anyObserver) -> Disposable in
            anyObserver.onNext("Hello word")
            return Disposables.create()
            }
            .subscribe(onNext: { (item) in
                print("订阅到:\(item)")
            })
            .disposed(by: self.disposeBag)
        }

并打印析构函数

  deinit {
        print("vc2执行了析构函数")
    }

我们能看得出来,这是一个非常普通的订阅操作,订阅里没有任何self的引用。
我们执行下,看下效果

*****vc1即将出现,此时引用计数为: 0
*****vc1的push及执行,此时引用计数为: 0
订阅到:Hello word
*****vc1已经消失,此时引用计数为: 8
*****vc1即将出现,此时引用计数为: 8
vc2执行了析构函数
*****vc1的push及执行,此时引用计数为: 0
订阅到:Hello word
*****vc1已经消失,此时引用计数为: 8
*****vc1即将出现,此时引用计数为: 8
vc2执行了析构函数

经过反复push与pop我们能看的出来,此时引用计数非常正常,并未造成内存泄露。

操作二

日常使用中,我们不大可能如此简单的使用订阅功能,我们经常会在创建序列的时候使用self。现在,假如我们仅仅是最简单的打印一下self(复杂使用效果一样),代码如下:

 Observable<Any>.create {(anyObserver) -> Disposable in
            print(self)
            anyObserver.onNext("Hello word")
            return Disposables.create()
            }
            .subscribe(onNext: { (item) in
                print("订阅到:\(item)")
            })
            .disposed(by: self.disposeBag)
        }

打印如下

<_01_RxSwift内存管理.ViewController: 0x7f8adf518340>
订阅到:Hello word
*****vc1已经消失,此时引用计数为: 8
*****vc1即将出现,此时引用计数为: 8
vc2执行了析构函数
*****vc1的push及执行,此时引用计数为: 0
<_01_RxSwift内存管理.ViewController: 0x7f8ae205b130>
订阅到:Hello word
*****vc1已经消失,此时引用计数为: 8
*****vc1即将出现,此时引用计数为: 8
vc2执行了析构函数

此时我们发现,依然没有问题。

操作三

如果我们只在订阅里使用self呢
代码如下

Observable<Any>.create {(anyObserver) -> Disposable in
            anyObserver.onNext("Hello word")
            return Disposables.create()
            }
            .subscribe(onNext: { (item) in
                print(self)
                print("订阅到:\(item)")
            })
            .disposed(by: self.disposeBag)
        }

打印结果:

*****vc1即将出现,此时引用计数为: 0
*****vc1的push及执行,此时引用计数为: 0
<_01_RxSwift内存管理.ViewController: 0x7fed7bf17960>
订阅到:Hello word
*****vc1已经消失,此时引用计数为: 8
*****vc1即将出现,此时引用计数为: 8
*****vc1的push及执行,此时引用计数为: 8
<_01_RxSwift内存管理.ViewController: 0x7fed7be32310>
订阅到:Hello word
*****vc1已经消失,此时引用计数为: 16
*****vc1即将出现,此时引用计数为: 16

问题出现了。此时vc2并没有执行析构,Rx的引用计数也没用释放。
解决办法很简单对self弱引用就可以了如下:

 Observable<Any>.create {(anyObserver) -> Disposable in
            anyObserver.onNext("Hello word")
            return Disposables.create()
            }
            .subscribe(onNext: {[weak self](item) in
                print(self)
                print("订阅到:\(item)")
            })
            .disposed(by: self.disposeBag)
        }

原理:
整个过程的持有关系如下:

image.png
图中有两个引用圈:
圈1:这个圈源码里已经写死的,我们无法更改。有这个圈也是必须的,因为sink本身是个临时变量,如果不能跟另外一个临时变量相互持有,两个临时变量都会被立即释放。
圈2:如果sink不会释放,sink强持有了selfself又持有了bagbag又持有了sink。导致圈2也被互相引用。
想打破这个局其实很简单,我们上述的解决方案就是在圈2持有1上做了手脚,弱引用一下self,此时self就跳出了圈2,当self被释放,bag也就被释放,sink也就被释放。圈1也就破了。
其实同时我们还能在持有3上搞一些事情。代码如下:
 Observable<Any>.create {(anyObserver) -> Disposable in
            anyObserver.onNext("Hello word")
            return Disposables.create()
            }
            .subscribe(onNext: {(item) in
                print(self)
                print("订阅到:\(item)")
            })
            .disposed(by:DisposeBag())
    
        }

我们把self持有的bag换成了一个临时变量。打印结果如下:

*****vc1的push及执行,此时引用计数为: 0
<_01_RxSwift内存管理.ViewController: 0x7fb540c26950>
订阅到:Hello word
*****vc1已经消失,此时引用计数为: 2
*****vc1即将出现,此时引用计数为: 2
vc2执行了析构函数
*****vc1的push及执行,此时引用计数为: 0
<_01_RxSwift内存管理.ViewController: 0x7fb543f0f2e0>
订阅到:Hello word
*****vc1已经消失,此时引用计数为: 2
*****vc1即将出现,此时引用计数为: 2
vc2执行了析构函数

能够看到问题同样也解决了,但是一般我们不能这样用。因为当执行到disposed(by:DisposeBag())时,整个序列会立即释放。我们整个观察序列就将毫无意义

操作四

如果我们创建与订阅同时引用了self,而我们只在订阅里弱引用的话,代码如下:

 Observable<Any>.create {(anyObserver) -> Disposable in
            print(self)
            anyObserver.onNext("Hello word")
            return Disposables.create()
            }
            .subscribe(onNext: { [weak self](item) in
                print(self)
                print("订阅到:\(item)")
            })
            .disposed(by: self.disposeBag)
        }

我们再来打印:

*****vc1即将出现,此时引用计数为: 0
*****vc1的push及执行,此时引用计数为: 0
<_01_RxSwift内存管理.ViewController: 0x7fba7bc20690>
Optional(<_01_RxSwift内存管理.ViewController: 0x7fba7bc20690>)
订阅到:Hello word
*****vc1已经消失,此时引用计数为: 8
*****vc1即将出现,此时引用计数为: 8
vc2执行了析构函数
*****vc1的push及执行,此时引用计数为: 0
<_01_RxSwift内存管理.ViewController: 0x7fba7be332d0>
Optional(<_01_RxSwift内存管理.ViewController: 0x7fba7be332d0>)
订阅到:Hello word
*****vc1已经消失,此时引用计数为: 8
*****vc1即将出现,此时引用计数为: 8
vc2执行了析构函数

毫无问题,依然成功释放。

结论:

我们使用序列的时候,只需要对subscribe里self进行弱引用,就能解决普通使用中的循环引用问题

上一篇 下一篇

猜你喜欢

热点阅读