I’m a fledgling iPhone developer, so be easy on me.
I’m trying to develop a simple app that will show the time and then tick every second. I feel like I’m missing something here with memory management, but my skills are too fresh to really know what I’m missing.
I’m creating a label straight to the main window (really simple app) and trying to update the label through and NSTimer. Here is my bit of code, it’s still a little messy.
@synthesize label, theDate;
@synthesize window;
- (void)tick
{
theDate = [[NSDateFormatter alloc] init];
[theDate setDateFormat:@"hh:mm:ss"];
NSString* currentTime = [theDate stringFromDate:[NSDate date]];
label.text = [[NSString alloc] initWithFormat:@"%d",currentTime];
[currentTime release];
}
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
CGRect rect = CGRectMake(10, 200, 300, 20);
label = [[UILabel alloc] initWithFrame:rect];
label.textAlignment = UITextAlignmentCenter;
[self.window addSubview:label];
[NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(tick)
userInfo:nil
repeats:YES];
[self.window makeKeyAndVisible];
return YES;
}
The @synthesize‘d ivars are @propertys in the .h file and the ivars get released in dealloc.
Thanks!
You have a number of memory problems here:
theDatebut not releasing it, so it’s leaking.currentTimedespite not having an owning reference, so you’ll likely see crashes in the autorelease pool.label.textbut not releasing it; either label.text is a retaining property, in which case you are leaking that string by double-retaining it, or label.text is not retaining, in which case you are leaking the string by never releasing it (except for the very last one, in dealloc)I’d strongly suggest you read Apple’s memory management guide.
Also, unrelated to the memory issues, you are using
%dto try to show a string instead of%@, so you’ll get the numeric value of the pointer address rather than the contents of the string.