zoukankan      html  css  js  c++  java
  • 防止 NSTimer retain 作为 target 的 self

    先吐槽一下这个标题,空格略蛋疼,不像中文,但是不写空格看上去则更诡异,求解决方案……

    NSTimer会retain它的target,这样如果在控制器当中定义一个NSTimer,target指定为self,则会引起循环引用。

    解决方案和防止block引用self一样,第一步需要把NSTimer的操作封装到一个block里,第二步则需要传递一个self的弱引用给block。

    首先定义一个NSTimer的分类:

     1 #import <Foundation/Foundation.h>
     2 
     3 @interface NSTimer (BlockSupport)
     4 
     5 + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval block:(void(^)())block repeats:(BOOL)repeats;
     6 
     7 @end
     8 
     9 #import "NSTimer+BlockSupport.h"
    10 
    11 @implementation NSTimer (BlockSupport)
    12 
    13 + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval block:(void(^)())block repeats:(BOOL)repeats {
    14     return [self scheduledTimerWithTimeInterval:interval target:self selector:@selector(blockInvoke:) userInfo:[block copy] repeats:repeats];
    15 }
    16 
    17 + (void)blockInvoke:(NSTimer *)timer {
    18     void (^block)() = timer.userInfo;
    19     if (block) {
    20         block();
    21     }
    22 }
    23 
    24 @end

    这个分类支持使用Block创建NSTimer,把操作传递到了万能对象userInfo里面,之后在控制器当中以这样的方式创建:

    1     __block typeof(self) weakSelf = self;
    2     _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 block:^{
    3         [weakSelf doSth];
    4     } repeats:YES];

    如此一来,NSTimer就不会令控制器的引用计数+1了。

  • 相关阅读:
    Java 常用工具类
    Shiro 分析
    Oracle 恢复表操作内容
    Struts2 中的配置文件 package name 、namespace 以及 对象方法调用
    MySql 修改字符集
    命名空间、静态函数、实例函数
    Eclipse Tomcate 热部署
    Java Json
    Mybatis 存储过程调用
    HDFS源码分析心跳汇报之数据结构初始化
  • 原文地址:https://www.cnblogs.com/Steak/p/3825577.html
Copyright © 2011-2022 走看看