NSTimer保留目标对象引起循环引用的解决办法

未命名.png

直接上代码:
扩充NSTimer功能,用block打破循环引用,创建类别实现。代码如下:

NSTimer+BlockSupport.h

//  
//  NSTimer+BlockSupport.h  
//  NewDemo  
//  
//  Created by sj_w on 16/3/24.  
//  Copyright © 2016年 sj_w. All rights reserved.  
//  
  
#import <Foundation/Foundation.h>  
  
@interface NSTimer (BlockSupport)  
  
+ (NSTimer *)yy_scheduledTimerWithTimeInterval:(NSTimeInterval)interval  
                                          block:(void(^)())block  
                                        repeats:(BOOL)repeats;  
  
@end  

NSTimer+BlockSupport.m

//  
//  NSTimer+BlockSupport.m  
//  NewDemo  
//  
//  Created by sj_w on 16/3/24.  
//  Copyright © 2016年 sj_w. All rights reserved.  
//  
  
#import "NSTimer+BlockSupport.h"  
  
@implementation NSTimer (BlockSupport)  
  
+ (NSTimer *)yy_scheduledTimerWithTimeInterval:(NSTimeInterval)interval  
                                          block:(void(^)())block  
                                        repeats:(BOOL)repeats  
{  
    return [self scheduledTimerWithTimeInterval:interval  
                                         target:self  
                                       selector:@selector(yzt_blockInvoke:)  
                                       userInfo:[block copy]  
                                        repeats:repeats];  
}  
  
+ (void)yzt_blockInvoke:(NSTimer *)timer {  
    void (^block) () = timer.userInfo;  
    if (block) {  
        block();  
    }  
}  
  
@end  

打完收功。。。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容