iOS timer定時(shí)器正確使用方式

1. 初始化熙掺,添加定時(shí)器前先移除

[self.timer invalidate];
self.timer = nil;
self.timer = [NSTimer scheduledTimerWithTimeInterval:2.f target:self selector:@selector(lookforCard:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

2. 釋放timer

[self.timer invalidate];
self.timer = nil;

3. NSTimer不釋放原因

  • 原因是 Timer 添加到 Runloop 的時(shí)候狭姨,會(huì)被 Runloop 強(qiáng)引用蜕着;然后 Timer 又會(huì)有一個(gè)對(duì) Target 的強(qiáng)引用(也就是 self )

注意target參數(shù)的描述:
The object to which to send the message specified by aSelector when the timer fires. The timer maintains a strong reference to target until it (the timer) is invalidated.
注意:文檔中寫的很清楚,timer對(duì)target會(huì)有一個(gè)強(qiáng)引用宰译,直到timer is invalidated琐谤。也就是說蟆技,在timer調(diào)用 invalidate方法之前,timer對(duì)target一直都有一個(gè)強(qiáng)引用斗忌。這也是為什么控制器的dealloc 方法不會(huì)被調(diào)用的原因质礼。
方法的文檔介紹:
The receiver retains aTimer. To remove a timer from all run loop modes on which it is installed, send an invalidate message to the timer.
也就是說,runLoop會(huì)對(duì)timer有強(qiáng)引用飞蹂,因此几苍,timer修飾符是weak,timer還是不能釋放陈哑,timer的target也就不能釋放妻坝。

4. 解決辦法

  • viewWillDisappearviewDidDisappear中 invalidate
    這種方式是可以釋放掉的,但如果我只是想在離開此頁(yè)時(shí)要釋放惊窖,進(jìn)入下一頁(yè)時(shí)不要釋放刽宪,場(chǎng)景就不適用了
- (void)viewWillDisappear:(BOOL)animated
- (void)viewDidDisappear:(BOOL)animated
  • 添加一個(gè)NSTimer的分類,把target指給[NSTimer class]界酒,事件由加方法接收圣拄,然后把事件通過block傳遞出來
@interface NSTimer (Block)

+ (instancetype)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void(^)(NSTimer *timer))block;

@end

@implementation NSTimer (Block)

+ (instancetype)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void(^)(NSTimer *timer))block{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(trigger:) userInfo:[block copy] repeats:repeats];
    return timer;
}

+ (void)trigger:(NSTimer *)timer{
    void(^block)(NSTimer *timer) = [timer userInfo];
    if (block) {
        block(timer);
    }
}

@end
  • 使用示例
@interface SecondViewController ()

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [weakSelf doSomeThing];
    }];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)dealloc {
    [self.timer invalidate];
}

@end

5. invalidate方法注意事項(xiàng)

invalidate方法的介紹:
(1)This method is the only way to remove a timer from an NSRunLoop object. The NSRunLoop object removes its strong reference to the timer, either just before the invalidate method returns or at some later point.
(2)You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.
兩點(diǎn):
(1)invalidate方法是唯一能從runloop中移除timer的方式,調(diào)用invalidate方法后毁欣,runloop會(huì)移除對(duì)timer的強(qiáng)引用
(2)timer的添加和timer的移除(invalidate)需要在同一個(gè)線程中庇谆,否則timer可能不能正確的移除岳掐,線程不能正確退出

附:我的博客地址

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市饭耳,隨后出現(xiàn)的幾起案子串述,更是在濱河造成了極大的恐慌,老刑警劉巖寞肖,帶你破解...
    沈念sama閱讀 222,807評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件纲酗,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡新蟆,警方通過查閱死者的電腦和手機(jī)觅赊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,284評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來琼稻,“玉大人吮螺,你說我怎么就攤上這事∨练” “怎么了规脸?”我有些...
    開封第一講書人閱讀 169,589評(píng)論 0 363
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)熊咽。 經(jīng)常有香客問我,道長(zhǎng)闹丐,這世上最難降的妖魔是什么横殴? 我笑而不...
    開封第一講書人閱讀 60,188評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮卿拴,結(jié)果婚禮上衫仑,老公的妹妹穿的比我還像新娘。我一直安慰自己堕花,他們只是感情好文狱,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,185評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著缘挽,像睡著了一般瞄崇。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上壕曼,一...
    開封第一講書人閱讀 52,785評(píng)論 1 314
  • 那天苏研,我揣著相機(jī)與錄音,去河邊找鬼腮郊。 笑死摹蘑,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的轧飞。 我是一名探鬼主播衅鹿,決...
    沈念sama閱讀 41,220評(píng)論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼撒踪,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了大渤?” 一聲冷哼從身側(cè)響起制妄,我...
    開封第一講書人閱讀 40,167評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎兼犯,沒想到半個(gè)月后忍捡,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,698評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡切黔,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,767評(píng)論 3 343
  • 正文 我和宋清朗相戀三年砸脊,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片纬霞。...
    茶點(diǎn)故事閱讀 40,912評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡凌埂,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出诗芜,到底是詐尸還是另有隱情瞳抓,我是刑警寧澤,帶...
    沈念sama閱讀 36,572評(píng)論 5 351
  • 正文 年R本政府宣布伏恐,位于F島的核電站孩哑,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏翠桦。R本人自食惡果不足惜横蜒,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,254評(píng)論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望销凑。 院中可真熱鬧丛晌,春花似錦、人聲如沸斗幼。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,746評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)蜕窿。三九已至谋逻,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間桐经,已是汗流浹背斤贰。 一陣腳步聲響...
    開封第一講書人閱讀 33,859評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留次询,地道東北人荧恍。 一個(gè)月前我還...
    沈念sama閱讀 49,359評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親送巡。 傳聞我的和親對(duì)象是個(gè)殘疾皇子摹菠,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,922評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容