在测试我的应用程序是否存在内存泄漏时,我发现每当我以一个间隔启动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 { } @endWhen 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; } @endcode: .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.
更多推荐
发布评论