开发者

Objective-C memory management - pretty sure I'm doing this all wrong

After 3 hours or so, I've finally managed to fix a memory leak in a view controller. The leak was caused by a UIPickerView that has its property set to 'retain' in the header file.

The following code managed to fix it:

- (void)viewDidLoad {
    [super viewDidLoad];    
    myPicker = [[[UIPickerView alloc] initWithFrame:CGRectZero]autorelease];
}

- (void)dealloc {
    [super dealloc];
    [myPicker release];
    myPicker = nil;
}

Please don't tell me how shocking this code is... I know it's b开发者_C百科ad. I've got a release, and an autorelease. Problem is, if I change or remove any part of the above, the memory leak returns.

I though I knew how objective C memory management works, obviously not...

Why does the above code fix the memory leak, and what might a correct version of the code look like?

-

EDIT:

If anyone has the same problem, or is interested - the problem was that one of the other objects in my class was set to 'retain' rather than 'assign'. (If you don't own an object, it should have the property assign, not retain).

Like Cannondale said, removing the extra retain fixes everything, and only one release is necessary.


You must be doing a retain on myPicker somewhere else in your code. Your myPicker allocation line will release that memory as soon as the stack unrolls for the viewDidLoad call (that is what the autorelease is telling it do do).

You must be doing a retain somewhere after that point, if not then your [myPicker release] will be trying to free unallocated memory with unpredictable results.

What you should be doing is allocating the memory in viewDidLoad (so remove the autorelease). Make sure you don't retain the object anywhere else and release myPicker from the dealloc.

Also ... what bbum said re the dealloc ;)


What Cannonade said. This should work:

myPicker = [[UIPickerView alloc] initWithFrame:CGRectZero];

Your dealloc is busted, too. Call to super always has to be last (think about it) and that can lead to undefined behavior.

- (void)dealloc {
    [myPicker release];
    myPicker = nil;
    [super dealloc];
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜