最近在做音视频播放器发现了一些crash问题,在这里做下记录。
一、AVPlayerItem remove KVO监听时Ceash
- Crash信息:
An instance 0x174204bc0 of class AVPlayerItem was deallocated while key value observers were still registered with it. Current observation info: <NSKeyValueObservationInfo 0x170626580> (
<NSKeyValueObservance 0x17444a4a0: Observer: 0x1702c2920, Key path: status, Options: <New: YES, Old: YES, Prior: NO> Context: 0x0, Property: 0x170844ef0>
<NSKeyValueObservance 0x174844cb0: Observer: 0x1702c2920, Key path: playbackBufferEmpty, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x170845130>
<NSKeyValueObservance 0x174843240: Observer: 0x1702c2920, Key path: playbackLikelyToKeepUp, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x1708453a0>
)
-
发生平台
WX20190917-171002@2x.png -
Crash原因
添加观察者的方式:
[_radioItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
[_radioItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
[_radioItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
[_radioItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
只在iOS10的系统上出现这个Crash,AVPlayerItem被释放了,没有有移除相关的通知监听;
在调用addObserver添加观察者后,KVO并不会对观察者进行强引用,所以要注意观察者对象的生命周期,否则如果观察者被释放会导致Crash。
KVO的addObserver和removeObserver需要是成对的,如果重复remove则会导致Crash,如果在调用removeObserver之前先将被观察者释放导致上面的Crash(在ios10系统上会发生)。
暂时的解决方案是创建一个强指针变量来引用该AVPlayerItem实例,再在合适的时间去手动清除引用
网友评论