开发者

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


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


They declared the formatter as static so the intention is to keep the formatter alive for the entire lifetime of the application. This would be for performance reasons and may be a pre-mature optimization so do not take this as a best practice in future development of your own.

//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];
}


setText just gets a string (not the formatter itself), so the formatter is not retained. My bet is that they use the formatter somewhere else in the controller and so it get released in dealloc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜