美文网首页
NSTimer保留目标对象引起循环引用的解决办法

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

作者: wsj_2012 | 来源:发表于2018-03-29 11:05 被阅读0次
未命名.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  

打完收功。。。

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/vpfmcftx.html