NSTimer泄漏内存(CFArray?)(NSTimer leaking memory (CFArray?))

编程入门 行业动态 更新时间:2024-10-23 12:31:39
NSTimer泄漏内存(CFArray?)(NSTimer leaking memory (CFArray?))

在测试我的应用程序是否存在内存泄漏时,我发现每当我以一个间隔启动NSTimer时,它会显示CFArray(store-deque)和CFArray(可变变量)的大小不断增长。 在我的实际应用程序中,Malloc 16和Malloc 32等与CFArray一起增加了大小。

问题:如何阻止这种“泄漏”?

代码:.h

@interface ViewController : UIViewController { NSTimer *timerClock; int timer; } @end

代码:.m

- (void)viewDidLoad { [super viewDidLoad]; timer = 0; timerClock = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(counter) userInfo:nil repeats:YES]; } - (void)counter { } @end

When testing my app for memory leaks I discovered that whenever I start NSTimer with an interval, it shows that CFArray (store-deque) and CFArray (mutable-variable) keeps growing in size. In my actual app Malloc 16 and Malloc 32 etc increases in size alongside with the CFArray.

Question: how do I stop this "leak"?

code: .h

@interface ViewController : UIViewController { NSTimer *timerClock; int timer; } @end

code: .m

- (void)viewDidLoad { [super viewDidLoad]; timer = 0; timerClock = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(counter) userInfo:nil repeats:YES]; } - (void)counter { } @end

最满意答案

你解雇视图控制器时是否看到了这个? 我问这个是因为重复的NSTimer保持对其target的强引用,如果你在解除视图控制器时没有invalidate计时器invalidate ,你将泄漏计时器和控制器本身,因为你将有一个强大的参考周期(控制器和NSTimer之间的保持周期 。

顺便说一下,不要试图在控制器的dealloc方法中invalidate ,因为在强引用循环中, dealloc永远不会被调用。 通常人们会在viewDidDisappear invalidate 。 而且,显然,如果你要在viewDidDisappear你的计时器invalidate ,你可能应该在viewDidAppear而不是viewDidLoad创建它,以确保平衡你的计时器创建与其invalidate调用。

Are you seeing this when you dismiss your view controller? I ask this because a repeating NSTimer keeps a strong reference to its target and if you don't invalidate the timer when you dismiss the view controller, you'll leak both the timer and the controller itself because you will have a strong reference cycle (a.k.a. a retain cycle) between the controller and the NSTimer.

By the way don't try to invalidate in the controller's dealloc method, because with the strong reference cycle, dealloc will never get called. Often people will invalidate in viewDidDisappear. And, clearly, if you're going to invalidate your timer in viewDidDisappear, you probably should be creating it in viewDidAppear rather than viewDidLoad, to make sure you balance your creation of the timer with its invalidate calls.

更多推荐

本文发布于:2023-07-27 17:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293584.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存   NSTimer   CFArray   memory   leaking

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!