问题
I have an NSTimer that fires off every second, and on that second I update a UILabel by setting the text property like so:
remainglbl.text = [NSString stringWithFormat:@"%i:%02i", var1, var2];
It works fine, but when I run it in xcode with Start With Performance Tool -> Leaks, it appears that the memory just keeps on climbing and climbing and climbing.
From my understanding, the string should be autoreleased (although I never see the memory decrease, or stop increasing).
Is this a memory leak? Is there a better way I can do this to keep my memory usage in check?
Thanks!
Update: code to create the timer is as follows:
timeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTime:) userInfo:nil repeats:YES];
code to cleanup at timer finish is as follows:
[timeTimer invalidate];
[timeTimer release];
timeTimer = nil;
Anything wrong with this? I thought the memory might be freed once the timer finishes, but it doesn't.
回答1:
I believe the problem was that I did not understand the performance tools. Running with the Activity Monitor does not show increasing memory usage.
回答2:
Just out of curiosity, does the problem still occur if you use [remainingLbl setText: ] instead of setting the property? Your code looks fine... the memory should be cleaned up since stringWithFormat autoreleases the string.
One other thing to try: when you create threads in Objective-C you have to wrap all the code in an NSAutoreleasePool so that the things you create during the thread's execution are cleaned up. That shouldn't make a difference here as one should already exist - but it's worth a shot.
来源:https://stackoverflow.com/questions/817550/uilabel-memory-leak