NSTimer注意内存泄露(真该死)
NSTimer可以用來執(zhí)行一些定時任務(wù),比較常用的方法就是:
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;?
可是,仔細看官方文檔中對于參數(shù)target的說明,可以看到這樣一段:
target
The object to which to send the message specified by?aSelector when the timer fires. The timer maintains a strong reference to this object until it (the timer) is invalidated.
也就是說,NSTimer會強引用target.?
那么如果我們按照通常的用法,在view controller中創(chuàng)建一個timer
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];就會帶來循環(huán)引用,viewController的dealloc()方法不會正確調(diào)用,從而導(dǎo)致內(nèi)存泄漏。
?
所以正確的做法,如果是在view controller中持有了NSTimer的對象,那么需要確保在view controller關(guān)閉之前,執(zhí)行如下方法:
[timer invalidate];有些人推薦是在viewDidDisappear的時候調(diào)用這個方法,但在部分業(yè)務(wù)邏輯中,跳轉(zhuǎn)到下一個頁面的時候并不是一定需要停止這個定時器的;所以需要根據(jù)自己的需要來調(diào)整。
?
另外,多說一句,看到有些代碼中使用timer的時候,定義的selector都沒有定義參數(shù)的,然后根據(jù)官方文檔,
The selector should have the following signature:?timerFireMethod: (including a colon to indicate that the method takes an argument). The timer passes itself as the argument, thus the method would adopt the following pattern:
- (void)timerFireMethod:(NSTimer *)timer;?
也就是說,這個selelctor實際上是需要帶上timer作為參數(shù)的。
?
聯(lián)想到上一篇談到NSNotificationCenter 的文章,
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;?
里面對于selector其實也說得很清楚,也是需要帶上一個參數(shù)而且只能帶上一個NSNotification的對象作為參數(shù)的.
notificationSelector
Selector that specifies the message the receiver sends?notificationObserver to notify it of the notification posting. The method specified by?notificationSelector must have one and only one argument (an instance of?NSNotification).
The End.
原文:http://www.cnblogs.com/agger0207/p/4419348.html
NSTimer 會強持有所在的 target
?
轉(zhuǎn)載于:https://www.cnblogs.com/benbenzhu/p/4832651.html
總結(jié)
以上是生活随笔為你收集整理的NSTimer注意内存泄露(真该死)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ibatis Parameter ind
- 下一篇: in-place数据交换