zoukankan      html  css  js  c++  java
  • NSTimer解除循环引用

    NSTimer作为一个经常使用的类,却有一个最大的弊病,就是会强引用target。造成调用timer很麻烦。稍有不慎就造成内存泄漏。

    下面就是为解决问题做的封装。

    直接上代码:


    #import <Foundation/Foundation.h>


    @interface LZLTimer : NSObject


    -(void)startTimerInterval:(NSTimeInterval)ti target:aTarget selector:(SEL)selector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;


    @end



    #import "LZLTimer.h"

    @interface LZLWeakTimerTarget : NSObject


    @property (nonatomic,weak) id target;

    @property (nonatomic,assign) SEL selector;


    - (void)timerDidFire:(NSTimer *)timer;


    @end


    @implementation LZLWeakTimerTarget


    - (void)timerDidFire:(NSTimer *)timer {

        if(_target) {

            //消除arc警告

            IMP imp = [_target methodForSelector:_selector];

            if ([NSStringFromSelector(_selector) hasSuffix:@":"]) {

                void (*func)(id, SEL, id) = (void *)imp;

                func(_target, _selector, timer);

            }else {

                void (*func)(id, SEL) = (void *)imp;

                func(_target, _selector);

            }

        } else {

            [timer invalidate];

        }

    }


    @end


    @interface LZLTimer () {

        NSTimer *_timer;

    }


    @end


    @implementation LZLTimer


    -(void)dealloc {

        if (_timer!=nil) {

            [_timer invalidate];

            _timer = nil;

        }

    }


    -(void)startTimerInterval:(NSTimeInterval)ti target:aTarget selector:(SEL)selector userInfo:(id)userInfo repeats:(BOOL)yesOrNo {

        if (nil == _timer) {

            WMWeakTimerTarget *weakTarget = [[WMWeakTimerTarget alloc] init];

            weakTarget.target = aTarget;

            weakTarget.selector = selector;


            _timer = [NSTimer scheduledTimerWithTimeInterval:ti target:weakTarget selector:@selector(timerDidFire:) userInfo:userInfo repeats:yesOrNo];

        }

    }


    @end


  • 相关阅读:
    SQLSERVER调用DLL程序
    RAISERROR语句
    SQLSERVER表联结(INNER JOIN,LEFT JOIN,RIGHT JOIN,FULL JOIN,CROSS JOIN,CROSS APPLY,OUTER APPLY)
    SQL Server在存储过程中编写事务处理代码的三种方法
    找出表中缺失的连续数据(如:2,4,7,9;需要找出:1,3,5,6,8的数据)
    sqlserver用于统计表索引情况
    你需要了解的HTTP协议
    自己实现一个类似 jQuery 的函数库
    JS 函数 学习笔记
    JS 数组 学习笔记
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/6921065.html
Copyright © 2011-2022 走看看