r/simpleios • u/IosNoob • Jul 21 '12
Need help with memory leaks
Hi All, I'm trying to implement some basic routines to draw on a view controller, and am finding the app leak memory at a fast rate when run. I can't seem to figure this out despite looking at endless links in google. Here's my code:
-(void)TVprintNumAndChar:(int)x: (int)y:(int)num:(unsigned char)c
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 20, 20)];
label.backgroundColor = [UIColor blackColor];
label.textColor = [UIColor whiteColor];
label.font = [UIFont systemFontOfSize:12];
label.text = [NSString stringWithFormat:@"%2d%c", num, c];
[self.view addSubview:label];
[label release];
}
This lives in a ViewController and is being called like:
[self TVprintNumAndChar: x: y: 33: 'a'];
I let the app run and Activity Monitor eats about 100kb a second. Let it run and eventually 'Springboard' and the simulator run out of memory and lock up. I comment out the line, and it's stable.
Any ideas?
2
u/youvechanged Jul 21 '12
I'm no expert but it looks to me like every time you run that code an additional label is created and added to your view. You need to either: a:) remove the existing label (if present) with removeFromSuperview method or b:) keep a reference to your label (an ivar, property or IBOutlet) and simply change its' text in your method.
1
u/buffering Jul 21 '12
To do custom drawing you would subclass
UIViewand implement the-drawRect:method. You would then call the-setNeedsDisplaymethod whenever your view needs to be redrawn.Your view controller would create this view eitiher in a NIB or in its
-loadViewmethod:UIKit offers many classes and extensions for drawing. For example:
See the NSString UIKit Extensions for more string drawing methods.
There's also CoreGraphics, which is the underlying C API for drawing in iOS and OS X. See the iOS Drawing and Printing Guide for more info.