日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

NSTimer注意内存泄露(真该死)

發(fā)布時間:2023/12/2 编程问答 56 豆豆
生活随笔 收集整理的這篇文章主要介紹了 NSTimer注意内存泄露(真该死) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

  

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。