开发者

iOS: NSDateFormatter memory leak / viewDidUnload

I've got a view controller that after leaving the stack, shows a memory leak in the Leaks instrument. After reading lots of posts about the NSDateFormatter bug, and implementing the setDateFormat 'Z' workaround, I'm still leaking memory (accord开发者_运维百科ing to Instruments).

In my header:

NSDateFormatter *dfm;
...
@property (nonatomic, retain) NSDateFormatter *dfm;

In my implementation:

@synthesize dfm;
...
- (void) viewDidLoad {
    [super viewDidLoad];
    dfm = [[NSDateFormatter alloc] init];
    [self.dfm setDateFormat:@"h:mma Z"]; // leaks with & without this line
}
...
- (void)viewDidUnload {
    //SOLUTION: This method was never being called. Needed to use dealloc, per the answer below.
    [dfm release];
    self.dfm = nil;
    [super viewDidUnload];
}

Anything stand out as incorrect? The only thing I do with dfm in this class is call stringFromDate in a few places to return autoreleased strings that I use with UILabels.

Thanks in advance.


You can't rely on viewDidUnload to be called. You also need:

- (void)dealloc {
    self.dfm = nil;
    // whatever else you need
    [super dealloc];
}

You only need to self.dfm = nil because the default synthesized setter will do the release.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜