NSTimer注意内存泄露(真该死)
NSTimer可以用來執行一些定時任務,比較常用的方法就是:
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;?
可是,仔細看官方文檔中對于參數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中創建一個timer
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];就會帶來循環引用,viewController的dealloc()方法不會正確調用,從而導致內存泄漏。
?
所以正確的做法,如果是在view controller中持有了NSTimer的對象,那么需要確保在view controller關閉之前,執行如下方法:
[timer invalidate];有些人推薦是在viewDidDisappear的時候調用這個方法,但在部分業務邏輯中,跳轉到下一個頁面的時候并不是一定需要停止這個定時器的;所以需要根據自己的需要來調整。
?
另外,多說一句,看到有些代碼中使用timer的時候,定義的selector都沒有定義參數的,然后根據官方文檔,
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作為參數的。
?
聯想到上一篇談到NSNotificationCenter 的文章,
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;?
里面對于selector其實也說得很清楚,也是需要帶上一個參數而且只能帶上一個NSNotification的對象作為參數的.
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
?
轉載于:https://www.cnblogs.com/benbenzhu/p/4832651.html
總結
以上是生活随笔為你收集整理的NSTimer注意内存泄露(真该死)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ibatis Parameter ind
- 下一篇: in-place数据交换