NStimer 的扩展使用

本文介绍了一个使用Objective-C扩展类解决NSTimer与视图循环引用问题的方法,通过自定义调度器避免了循环引用,确保了应用的稳定性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题 由于nstimer 和 视图 非常容易循环引用 

1.这里提供一个一个很好的解决办法 

#import <Foundation/Foundation.h>


@interface NSTimer (Support)

+ (NSTimer *)wx_scheduledTimerWithTimeInterval:(NSTimeInterval)interval

                                         block:(void(^)())block

                                       repeats:(BOOL)repeat;

@end






#import "NSTimer+Support.h"


@implementation NSTimer (Support)


+ (NSTimer *)wx_scheduledTimerWithTimeInterval:(NSTimeInterval)interval

                                         block:(void(^)())block

                                       repeats:(BOOL)repeat {

    

    // 传入的 self 其实就是 NSTimer ,是一个类对象 (和实例对象区分开)

    return [self scheduledTimerWithTimeInterval:interval target:self selector:@selector(support_blockInvoke:) userInfo:[block copy] repeats:YES];

}


+ (void)support_blockInvoke:(NSTimer *)timer {

    void(^block)() = timer.userInfo;

    if (block) {

        block();

    }

}



@end



//这是一个扩展类别 


// 解释一下为什么这样可以 

对于这个方法 target:self; 然后因为我们目标方法是support_blockInvoke:这个是一个加方法,显然这个self 就是 Class(不是实例就不会导致循环引用)

[self scheduledTimerWithTimeInterval:interval target:self selector:@selector(support_blockInvoke:) userInfo:[block copy] repeats:YES]





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值