1
votes

I've been spinning on this for 2 hours now, so thought I'd post here for some advice.

In my viewDidLoad method, I do:

UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 600)];
...
UIView *contactsRow = [self generateContactsRow];
contactsRow.frame = CGRectMake(10, tableMaxY, 300, 56);
...
[scrollView addSubview:contactsRow];
[self.view addSubview:scrollView];
[scrollView release]; 

In [self generateContactsRow], I basically create a container view, load a bunch of other views (button, label, etc) inside, and return it.

UIView *containerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 0)] autorelease];
... (define stuff)
// set it
[containerView addSubview:imageView];
[containerView addSubview:textLabel];
[containerView addSubview:detailTextLabel];
[containerView addSubview:addButton];
[containerView addSubview:hr];

// and forget it
[imageView release];
[textLabel release];
[detailTextLabel release];
[addButton release];
[hr release];

return containerView;

The fact that I'm autoreleasing containerView is causing my app to crash. I return an alloc'd object, so I thought I had to release it somehow, and autorelease seemed the best way. If I remove it, things work fine, but won't I then have a memory leak?

Thanks

2
The code looks correct. Have you turned the NSZombieEnabled flag on to see if that truly is the case? - Brandon A
The snippet you posted is correct in terms of memory management. How are you initializing the objects you add to containerView? Try running the static analyzer and see if it catches anything. - titaniumdecoy
Use return [containerView autorelease]; And remove autorelease from UIView initialization. - Sudesh Kumar

2 Answers

2
votes

Make the segment like the following

UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 600)];
...
UIView *contactsRow = [[self generateContactsRow] retain];
contactsRow.frame = CGRectMake(10, tableMaxY, 300, 56);
...
[scrollView addSubview:contactsRow];
[self.view addSubview:scrollView];
[contactsRow release]; 
[scrollView release]; 

I am retaining the contactsRow here and releasing that after I have it as subview to the scrollView. So there won't be any memory leak.

0
votes

You can release it in viewdidunload or viewwillDisapper methods...