You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Objective-C使用定时器调用函数时出现Unrecognized selector错误求助

问题原因与解决方法

错误原因

你遇到的unrecognized selector sent to class错误,核心问题是定时器的target参数传错了:

  • 你给Timer.scheduledTimer传的target: timerClass.self是类对象,定时器会尝试向这个类发送cycle消息;
  • 但你的cycle是实例方法(没有class或static修饰),类对象无法响应实例方法,所以运行时找不到对应方法,抛出错误。

解决步骤

  1. 修正定时器的target参数
    把target: timerClass.self改成当前类的实例对象,比如如果这段代码写在某个视图控制器或自定义类的实例方法/初始化方法里,直接用self:

    var synchronizer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(cycle), userInfo: nil, repeats: true)
    

    注意:如果是在类的属性初始化里直接写,可能需要用延迟初始化(lazy var),避免self还未完全初始化的问题:

    lazy var synchronizer: Timer = {
        Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(cycle), userInfo: nil, repeats: true)
    }()
    
  2. 确保方法的可见性
    你的cycle已经加了@objc修饰,这部分没问题,保证了OC运行时能识别这个方法。

额外优化建议

  • DateFormatter每次在cycle里创建会浪费性能,建议把它声明为类的属性:
    let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // 根据需求设置格式
        return formatter
    }()
    
  • 数组截断可以简化写法,不用dropLast再赋值:
    if data.timeArray.count > 30 {
        data.timeArray.removeLast(data.timeArray.count - 30)
    }
    
  • 你最后把timeString.text赋值为ss,会覆盖之前的ts内容,如果需要同时显示时间和速度,要调整字符串拼接逻辑。

内容的提问来源于stack exchange,提问作者NoMoreMemes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 18:51:31