I'm reading through the Big Nerd Ranch book on iOS programming and I had a question about the Hypnotime program they create in chapter 7.
At some point, they implement the following method:
- (void)showCurrentTime:(id)sender
{
NSDate *now = [NSDate date];
static NSDateFormatter *formatter = nil;
if (!formatter) {
formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
}
[timeLabel setText:[formatter stringFromDate:now]];
}
My question is about NSDateFormatter *formatter
. The formatter gets created with alloc
and init
. I always learnt that anything with alloc
needs to be released somewhere, right? When formatter
gets passed to timeLabel
, doesn't timeLabel
send retain
to it? And can't (shouldn't?) I subsequently release formatter
?
I browsed through the code on the next couple of pages and I can't find any release message anywhere, except for a release
being send to timeLabel
in dealloc
.
Am I mixing things up here? Is there a reason why formatter
shouldn't be released by me? I want to be a good memory citizen. Any help is appreciated :)
Because of the static
keyword the formatter
will stay available until next time the method is called, as a global variable - well, without being global
See wikipedia entry about static
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With