Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS basic memory management

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 retainto 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 :)

like image 412
Joris Ooms Avatar asked Oct 10 '22 08:10

Joris Ooms


1 Answers

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

like image 135
epatel Avatar answered Oct 13 '22 03:10

epatel