25-內存管理之定時器

一 CADisplayLink、NSTimer使用注意
  • CADisplayLink吗冤、NSTimer會對target產(chǎn)生強引用又厉,如果target又對它們產(chǎn)生強引用九府,那么就會引發(fā)循環(huán)引用

示例代碼如下

  • CADisplayLink
@property (strong, nonatomic) CADisplayLink *link;

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 保證調用頻率和屏幕的刷幀頻率一致,60FPS
    self.link = [CADisplayLink displayLinkWithTarget:self selector:@selector(linkTest)];
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)linkTest {
    NSLog(@"%s", __func__);
}

執(zhí)行幾秒后點擊退出當前控制器

執(zhí)行結果如下

1653926-2b14b150ac9547df.png

由打印結果可知覆致,雖然已經(jīng)控制器已經(jīng)消失了侄旬,但是沒有調用其dealloc方法,造成內存泄露.

  • NSTimer
@property (strong, nonatomic) NSTimer *timer;

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerTest {
    NSLog(@"%s", __func__);
}

- (void)dealloc {
    NSLog(@"%s", __func__);
    [self.timer invalidate];
}

執(zhí)行幾秒后點擊退出當前控制器

執(zhí)行結果如下

1653926-ecf4809af703c4af.png

由運行結果可知煌妈,控制器已經(jīng)消失了儡羔,但是仍然沒有調用其dealloc方法,導致內存泄露璧诵。

解決方案
  • 使用block
__weak typeof(self) weakSelf = self;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
    [weakSelf timerTest];
}];

運行結果

1653926-fa507d3d69b333e9.png

由運行結果可知汰蜘,控制器退出時,調用了其dealloc方法之宿,不會造成內存泄露鉴扫。

  • 使用代理對象(NSProxy)
  • CADisplayLink

Proxy

// Proxy.h
@interface Proxy : NSObject
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end

// Proxy.m
@implementation Proxy
+ (instancetype)proxyWithTarget:(id)target {
    Proxy *proxy = [[Proxy alloc] init];
    proxy.target = target;
    return proxy;
}

- (id)forwardingTargetForSelector:(SEL)aSelector {
    return self.target;
}
@end

使用CADisplayLink

self.link = [CADisplayLink displayLinkWithTarget:[Proxy proxyWithTarget:self] selector:@selector(linkTest)];
[self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

運行結果

1653926-244ab58c1b421c70.png
  • NSTimer
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[Proxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

運行結果

1653926-f64b7d101a1aa77b.png
直接繼承NSProxy
// Proxy1.h文件
@interface Proxy1 : NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end

// Proxy1.m文件
@implementation Proxy1
+ (instancetype)proxyWithTarget:(id)target {
    // NSProxy對象不需要調用init,因為它本來就沒有init方法
    Proxy1 *proxy = [Proxy1 alloc];
    proxy.target = target;
    return proxy;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    return [self.target methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    [invocation invokeWithTarget:self.target];
}
@end

  • NSProxy的特點
Proxy *proxy1 = [Proxy proxyWithTarget:self];
Proxy1 *proxy2 = [Proxy1 proxyWithTarget:self];

NSLog(@"%d %d",[proxy1 isKindOfClass:[ViewController class]],[proxy2 isKindOfClass:[ViewController class]]);

運行結果

1653926-1370f466197b108b.png

分析:因為Proxy1是繼承自NSProxy,會直接進行消息轉發(fā)機制澈缺,所以執(zhí)行[proxy2 isKindOfClass:[ViewController class]])坪创,相當于vc執(zhí)行執(zhí)行isKindOfClass方法,而isKindOfClass內部也是進行了消息轉發(fā)姐赡,所以返回1莱预。

二 GCD定時器
  • NSTimer依賴于RunLoop,如果RunLoop的任務過于繁重项滑,可能會導致NSTimer不準時
  • 而GCD的定時器會更加準時

分裝GCD定時器類實例代碼如下

  • CSTimer.h
@interface CSTimer : NSObject

+ (NSString *)execTask:(void(^)(void))task
                 start:(NSTimeInterval)start
              interval:(NSTimeInterval)interval
               repeats:(BOOL)repeats
                 async:(BOOL)async;

+ (NSString *)execTask:(id)target
              selector:(SEL)selector
                 start:(NSTimeInterval)start
              interval:(NSTimeInterval)interval
               repeats:(BOOL)repeats
                 async:(BOOL)async;

+ (void)cancelTask:(NSString *)name;

@end

  • CSTimer.m
@implementation CSTimer

// 保存定時器的字典
static NSMutableDictionary *timers_;
// 信號量
dispatch_semaphore_t semaphore_;

// 初始化操作
+ (void)initialize {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        timers_ = [NSMutableDictionary dictionary];
        semaphore_ = dispatch_semaphore_create(1);
    });
}

+ (NSString *)execTask:(void (^)(void))task start:(NSTimeInterval)start interval:(NSTimeInterval)interval repeats:(BOOL)repeats async:(BOOL)async {
    // 如果認為不存在 開始時間小于0 重復并且時間小于0 則返回空
    if (!task || start < 0 || (interval <= 0 && repeats)) return nil;

    // 隊列 - 是主隊列還是并發(fā)隊列
    dispatch_queue_t queue = async ? dispatch_get_global_queue(0, 0) : dispatch_get_main_queue();

    // 創(chuàng)建定時器
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

    // 設置時間
    dispatch_source_set_timer(timer,
                              dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC),
                              interval * NSEC_PER_SEC, 0);

    // 保證線程安全
    dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
    // 定時器的唯一標識
    NSString *name = [NSString stringWithFormat:@"%zd", timers_.count];
    // 存放到字典中
    timers_[name] = timer;
    dispatch_semaphore_signal(semaphore_);

    // 設置回調
    dispatch_source_set_event_handler(timer, ^{
        task();

        if (!repeats) { // 不重復的任務
            [self cancelTask:name];
        }
    });

    // 啟動定時器
    dispatch_resume(timer);

    return name;
}

+ (NSString *)execTask:(id)target selector:(SEL)selector start:(NSTimeInterval)start interval:(NSTimeInterval)interval repeats:(BOOL)repeats async:(BOOL)async {
    if (!target || !selector) return nil;

    return [self execTask:^{
        if ([target respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            [target performSelector:selector];
#pragma clang diagnostic pop
        }
    } start:start interval:interval repeats:repeats async:async];
}

// 取消定時器操作
+ (void)cancelTask:(NSString *)name {
    if (name.length == 0) return;

    // 線程安全
    dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);

    dispatch_source_t timer = timers_[name];
    if (timer) {
        dispatch_source_cancel(timer);
        [timers_ removeObjectForKey:name];
    }

    dispatch_semaphore_signal(semaphore_);
}

外部調用

// 開始定時器操作
- (void)startTimer {
    // 1.使用block回調
    self.task = [CSTimer execTask:^{
        NSLog(@"111111 - %@", [NSThread currentThread]);
    } start:2.0 interval:1.0 repeats:YES async:YES];

    // 2.使用selector
//    self.task = [CSTimer execTask:self selector:@selector(doTask) start:2.0 interval:1.0 repeats:YES async:YES];
}

// 定時執(zhí)行任務
- (void)doTask {
    NSLog(@"doTask - %@", [NSThread currentThread]);
}

// 停止定時器
[CSTimer cancelTask:self.task];


本文參考:
路飛_Luck (http://www.reibang.com/p/07f7b96bb03f)
以及借鑒MJ的教程視頻
非常感謝.


項目連接地址 - MemoryManage-CADisplayLink+Timer

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末依沮,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子枪狂,更是在濱河造成了極大的恐慌危喉,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件州疾,死亡現(xiàn)場離奇詭異辜限,居然都是意外死亡,警方通過查閱死者的電腦和手機严蓖,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門薄嫡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人颗胡,你說我怎么就攤上這事毫深。” “怎么了毒姨?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵哑蔫,是天一觀的道長。 經(jīng)常有香客問我,道長闸迷,這世上最難降的妖魔是什么嵌纲? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任送火,我火速辦了婚禮单山,結果婚禮上俱诸,老公的妹妹穿的比我還像新娘暴匠。我一直安慰自己畸写,他們只是感情好藏姐,可當我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布望浩。 她就那樣靜靜地躺著伤锚,像睡著了一般酣栈。 火紅的嫁衣襯著肌膚如雪险胰。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天矿筝,我揣著相機與錄音起便,去河邊找鬼。 笑死窖维,一個胖子當著我的面吹牛榆综,可吹牛的內容都是我干的。 我是一名探鬼主播铸史,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼鼻疮,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了琳轿?” 一聲冷哼從身側響起判沟,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎崭篡,沒想到半個月后挪哄,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡琉闪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年迹炼,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片塘偎。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡疗涉,死狀恐怖,靈堂內的尸體忽然破棺而出吟秩,到底是詐尸還是另有隱情,我是刑警寧澤绽淘,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布涵防,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏壮池。R本人自食惡果不足惜偏瓤,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望椰憋。 院中可真熱鬧厅克,春花似錦、人聲如沸橙依。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽窗骑。三九已至女责,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間创译,已是汗流浹背抵知。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留软族,地道東北人刷喜。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像立砸,于是被迫代替她去往敵國和親掖疮。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內容