IOS memory management

I am reading a Big Nerd Ranch book on iOS programming, and I have a question about the Hypnotime program that 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. Formatting is created using allocand init. I always found out that something with allocshould be released somewhere, right? When formattergoes to timeLabel, doesn't send timeLabelto it retain? And can not (should not?) I subsequently release formatter?

I scanned the code on the next two pages, and I can not find any to issue a message in any place except what releasegoes on timeLabelin dealloc.

? , formatter ? . :)

+5
3

, , . , .

//static (even in a method) will allow formatter to live during entire app lifecycle
static NSDateFormatter *formatter = nil;

//Check if formatter has been set (this is not thread safe)
if (!formatter) {
    //Set it once and forget it, it wont be a leak, and it wont ever be released
    formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
}
+1

- static formatter - ,

. wikipedia static

+2

setText just gets the string (not the formatter itself), so the formatter is not saved. My bet is that they use the formatter somewhere else in the controller and therefore it is freed in dealloc

+1
source

All Articles