当前位置: 首页 > news >正文

GCD定时器DispatchSourceTimer崩溃问题

//
//  SecondaryViewController.swift
//  0401
//
//  Created by kqc on 2025/7/30.
//
/** 使用DispatchSourceTimer注意点* 1: suspend状态不能调用cancel方法会崩溃* 2: 重复调用resume或者suspend方法崩溃,必须成对出现* 3: 销毁时如果 resume() -> cancel() -> time = nil 会在特定机型崩溃偶发频率很高 如iPhone13,iPhone16等* 针对3的修改,在setCancelHandler中执行对应的销毁操作*/
import UIKitclass SecondaryViewController: UIViewController {var timer: DispatchSourceTimer?var count = 0override func viewDidLoad() {super.viewDidLoad()title = "测试DispatchTime"view.backgroundColor = .whiteaddNoti()createTimer()}override func viewWillDisappear(_ animated: Bool) {super.viewWillDisappear(animated)timer?.suspend()}override func viewWillAppear(_ animated: Bool) {super.viewWillAppear(animated)timer?.resume()}func createTimer() {timer = DispatchSource.makeTimerSource()timer?.schedule(deadline: .now(), repeating: .seconds(2), leeway: .milliseconds(100))timer?.setEventHandler(handler: DispatchWorkItem(block: {print("测试数据...")}))
//        To safely close a file descriptor or destroy a Mach port, a cancellation handler is required for that descriptor or port.timer?.setCancelHandler(handler: DispatchWorkItem(block: {[weak self] inself?.timer = nil}))}func stopTimer() {guard let timer = timer else {return}timer.suspend()}func recoverTimer() {guard let timer = timer else {return}timer.resume()}func closeTimer() {timer?.resume()timer?.cancel()
//        self.timer = nil
    }func delayAction() {DispatchQueue.main.asyncAfter(deadline: .now() + 1){self.count += 1print(self.count)}}deinit {closeTimer()removeNoti()debugPrint("销毁")}
}extension SecondaryViewController {func addNoti() {NotificationCenter.default.addObserver(self, selector: #selector(becomeActiveStatu), name: UIApplication.willEnterForegroundNotification, object: nil)NotificationCenter.default.addObserver(self, selector: #selector(resignActiveStatu), name: UIApplication.willResignActiveNotification, object: nil)}func removeNoti() {NotificationCenter.default.removeObserver(self)}@objc func becomeActiveStatu() {recoverTimer()}@objc func resignActiveStatu() {stopTimer()}}

 

http://www.sczhlp.com/news/2403/

相关文章:

  • 【直播预约】天翼云如何通过 DolphinScheduler 实现大数据自动化与全链路血缘,探索实践亮点!
  • 面经学习-ECDHE加密的TLS
  • 关于python环境库导出
  • 圆满闭幕|WAIC2025规模创历史新高,“灵掘”具身智能模型全球首发引全网关注
  • 案例故事 | 数据治理:某半导体巨头的数字化升级之路
  • 每日经济新闻专访:押注具身智能模型、不做硬件做“大脑”,网易能否啃下更复杂的“硬骨头”?
  • 一图读懂网易灵动“灵掘”与“机械智心”
  • 相合估计
  • 区间估计
  • 方差和回归分析
  • 人力资源系统如何解决群面问题的方法
  • 模板库
  • 相机标定原理
  • PostgreSQL认证培训授权考试中心(工信人才唯一授权指定)
  • 一些STL
  • AKShare 高频请求东财数据接口的异常问题及解决方案
  • C# Rsa加密(私钥加密、公钥解密、密钥格式转换、支持超大长度分段加密)
  • EDCA - 802.11e
  • 用C# 实现标准MD5WithRSA算法
  • 操作系统引导过程详解:从开机到进入系统的每一步
  • linux系统中查询中间件进程的for命令 - 一叶舟
  • Docker容器运行Windows11
  • 全局平衡二叉树
  • pygame小游戏打飞机_5多个敌人
  • 贪心算法
  • inux系统中查询中间件进程的for命令.19015328 - 一叶舟
  • 6.1.1 随机访问存储器
  • 垃圾邮件过滤的算法与技术:深入解析贝叶斯过滤与机器学习模型
  • 【完结13章】人工智能Ai Agent RAG云服务器python后端零基础实战课
  • 面经学习-HTTP优化