OC-内存管理-NSTimer

NSTimer 就是我们的定时器 可以满足我们很多业务需求 ,但是它会带来内存泄漏的隐患.

场景:在一个VC中设定一个全局定时器定时打印log,需要在pop该VC的时候 清除定时器 减少内存泄露

解决如下:

001 生命周期 处理

- (void)didMoveToParentViewController:(UIViewController *)parent{

     NSLog(@"didMoveToParent==%@",parent);

    //parent 就是当前的视图控制器的UINavigationController

    if (parent == nil) {

        [self.timer invalidate];

        self.timer = nil;

    }

}

002 设置消息转发 

@property (nonatomic,strong) id target;

class_addMethod([_target class], @selector(fire), (IMP)fireImp,"V@:");

self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:_target selector:@selector(fire) userInfo:nil repeats:YES];

  [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

void fireImp(id self,SEL _cmd){

    NSLog(@"fire.......fireImp");

}

- (void)dealloc{

    NSLog(@"VV dealloc");

    [self.timer invalidate];

    self.timer = nil;

}

003 中转代理

@interface RunTimeProxy : NSProxy

@property (nonatomic, weak) id target;

@end

#import "RunTimeProxy.h"

@implementation RunTimeProxy

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{

    return [self.target methodSignatureForSelector:sel];

}

- (void)forwardInvocation:(NSInvocation *)invocation{

    [invocation invokeWithTarget:self.target];

}

@end

在VC中引入代理

@property (nonatomic,strong) RunTimeProxy *proxy;

_proxy = [RunTimeProxy alloc];

    _proxy.target = self;

self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:_proxy selector:@selector(fire) userInfo:nil repeats:YES];

    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

- (void)fire{

    NSLog(@"fire.......");

}

- (void)dealloc{

    NSLog(@"VV dealloc");

    [self.timer invalidate];

    self.timer = nil;

}

 

原则是让timer 不直接持有self 通过一些self的马甲套路: NSObject对象消息转发以及中转代理代理weak引用self,这样可以在pop执行之后就可以执行析构函数dealloc函数清除timer 移除在runLoop中.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值