NSTimer+WeakTimer(解决循环引用分类)

不废话,看代码

//
//  NSTimer+WeakTimer.h
//  Copyright © 2018 YXFF. All rights reserved.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSTimer (WeakTimer)
+ (NSTimer *)scheduledWeakTimerWithTimeInterval:(NSTimeInterval)interval target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats;
@end

NS_ASSUME_NONNULL_END
//
//  NSTimer+WeakTimer.m
//  Copyright © 2018 YXFF. All rights reserved.
//

#import "NSTimer+WeakTimer.h"
@interface TimerWeakObject : NSObject
@property (nonatomic,weak) id target;
@property (nonatomic,assign) SEL selector;
@property (nonatomic,weak) NSTimer *timer;

- (void)fire:(NSTimer *)timer;
@end
@implementation TimerWeakObject
- (void)fire:(NSTimer *)timer {
    if (self.target) {
        if ([self.target respondsToSelector:self.selector]) {
            #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            [self.target performSelector:self.selector withObject:timer.userInfo];
        }
    }else {
        [self.timer invalidate];
    }
}

@end
@implementation NSTimer (WeakTimer)
+ (NSTimer *)scheduledWeakTimerWithTimeInterval:(NSTimeInterval)interval target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats {
    TimerWeakObject *object = [[TimerWeakObject alloc]init];
    object.target = aTarget;
    object.selector = aSelector;
    object.timer = [NSTimer scheduledWeakTimerWithTimeInterval:interval target:object selector:@selector(fire:) userInfo:userInfo repeats:repeats];
    
    return object.timer;
}
@end

欢迎纠错、留言、点赞😀

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 每天进步一点点点点点点点点点点点点点点点点点点点点点点点点点点点点点点~~从开始只能写几句话、模仿别人的观点,到现...
    一个帅气的名字呀阅读 18,637评论 4 31
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,840评论 4 61
  • 时间过得非常的快,转眼间已经是第三次见面会了,还记得第一次见面会的时候在去之前老师布置作业说要写一份作业,那个时候...
    冯波131419阅读 2,454评论 0 6
  • “同学们,你们在干嘛?”这天施寒刚下完课,看见教学楼外面自己班的学生正聚集在一堆,围观着什么。 “施老师,这里有一...
    氧化反应阅读 2,166评论 3 2
  • 收回权限 #给用户cacti赋予所有库的所有权限 GRANT ALL PRIVILEGES ON *.* ...
    think_lonely阅读 2,649评论 0 0

友情链接更多精彩内容