1: NSTimer不能置零导致VC不释放。导致内存泄露
1.1 解决的实例方法一:
import UIKit
class TwoViewController: UIViewController {
var customTimer:Timer?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.orange
customTimer = Timer.init(timeInterval: 1, target: self, selector: #selector(TwoViewController.timrClick(sender:)), userInfo: self, repeats: true)
RunLoop.current.add(customTimer!, forMode: RunLoopMode.commonModes)
}
func timrClick(sender:Timer) {
print("timrClick: \(sender.timeInterval)")
}
deinit {
print("\(object_getClass(self)) delloc")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
customTimer?.invalidate()
}
}
结果能不能释放控制器那, 有没有问题
- 1: 单纯是pop没有问题, 没有深层的push. 没有问题
- 2: 如果有深层的跳转, 比如当前的控制器的定时器是控制
倒计时
,图片轮播
的, 这样我们的push的时候 定时就停掉了,所以这个方法不可取
1.2 解决的实例方法二:
和方法一类似 但是在离开当前的视图的时候 做一个判断, 判断是pop还是push
具体步骤:
1: 视图展示的时候记录一下, 当前导航控制器的子控制器的数量
2: 视图离开(包括pop.push), 当前导航控制器的childVc的数量, 与之前的做一个比较
注: push.pop 是 压栈和出栈的过程, 修改navVc的子控制器的数量
import UIKit
class TwoViewController: UIViewController {
var vcCount = 0
var customTimer:Timer?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.orange
vcCount = (self.navigationController?.viewControllers.count)!
customTimer = Timer.init(timeInterval: 1, target: self, selector: #selector(TwoViewController.timrClick(sender:)), userInfo: self, repeats: true)
RunLoop.current.add(customTimer!, forMode: RunLoopMode.commonModes)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
guard let tmpCount = self.navigationController?.viewControllers.count else {
return
}
// 如果当前的控制器数量大于一开始的数量 说明是push
// 如果小于 说明是pop
if tmpCount < vcCount {
self.customTimer?.invalidate()
self.customTimer = nil
}
}
func timrClick(sender:Timer) {
print("timrClick: \(sender.timeInterval)")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.navigationController?.pushViewController(ThreeViewController(), animated: true)
}
deinit {
print("\(object_getClass(self)) delloc")
}
}