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

如何不借助Timer变量调用scheduledTimerWithTimeInterval并消除未使用警告?

解决Objective-C中Timer未使用警告的方法

嘿约翰,我来帮你搞定这个问题~

首先得理清一个关键点:你看到的那段带点语法的代码是Swift版本的NSTimer调用方式,直接放到Objective-C代码里肯定会报错,这就是你遇到“找不到属性”“Target未声明”的原因,两种语言的语法不兼容哦。

回到你的核心需求:消除“timer未被使用”的警告,同时不想保留悬空的Timer变量,这里给你几种Objective-C下的可行方案:

  • 方案1:直接不赋值给变量(最推荐,如果你不需要手动停止定时器)
    因为[NSTimer scheduledTimerWithTimeInterval:...方法会自动将定时器加入当前RunLoop,不需要你持有变量来维护它。直接写成一行,编译器就不会报未使用变量的警告了:

    [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(loadSeries:) userInfo:_response repeats:NO];
    
  • 方案2:用__unused标记变量(适合可能后续需要操作定时器的场景)
    如果你之后可能需要手动停止这个定时器,还是得声明变量,但可以用__unused关键字告诉编译器你故意不使用这个变量,从而消除警告:

    __unused NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(loadSeries:) userInfo:_response repeats:NO];
    
  • 方案3:临时屏蔽警告(适合特殊场景)
    如果你需要保留变量声明但又不想看到警告,也可以用编译器指令临时屏蔽这段代码的未使用变量警告:

    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wunused-variable"
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(loadSeries:) userInfo:_response repeats:NO];
    #pragma clang diagnostic pop
    

选哪个方案取决于你是否需要后续控制这个定时器——如果只是触发一次任务不需要停止,方案1最简洁;如果之后可能要取消定时器,方案2更合适。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:18:56