Skip navigation.
 
mlRe: [NSView removeFromSuperview] not affecting retain count
FROM : John C. Randolph
DATE : Mon Dec 20 20:50:54 2004

On Dec 18, 2004, at 11:29 PM, Julian Pellico wrote:



> Hi,
>
> I have a subclass of NSView ( say MyView) and a controller class (say
> MyViewController) that manages an instance of this view.
>
> In another controller class (a window controller) I have a method that
> does the following:
>
> - (void) removeMyViews
> {
>  for (int i = 0; i < [myViewControllers count]; i++) {
>  NSLog(@"--- 1 --- retainCount: %u", [[[myViewControllers
> objectAtIndex: i] view] retainCount]);
>  [[[myViewControllers objectAtIndex: i] view] removeFromSuperview];
>  NSLog(@"--- 2 --- retainCount: %u", [[[myViewControllers
> objectAtIndex: i] view] retainCount]);
>  }
>  [myViewControllers removeAllObjects];
> }
>
> When this method gets run, every time through the loop the retain
> count is the same in the 2 log lines.

That's because -removeFromSuperview sends -autorelease, not -release,
to the view you're removing. The retain count won't decrement until the
autorelease pool is released. This saves you the trouble of sending an
additional -retain/-release when you want to move a view from one
superview to another:

- moveToView:(NSView *) newView
{
[self removeFromSuperview];
[newView addSubview:self];
}

instead of:

- moveToView:(NSView *) newView
{
[self retain];
[self removeFromSuperview];
[newView addSubview:self];
[self release];
}


> Isn't this contrary to the documentation of NSView?

Nope.

-jcr



John C. Randolph <<email_removed>> (408) 974-8819
Sr. Cocoa Software Engineer,
Apple Worldwide Developer Relations
http://developer.apple.com/cocoa/index.html

Related mailsAuthorDate
ml[NSView removeFromSuperview] not affecting retain count Julian Pellico Dec 19, 08:29
mlRe: [NSView removeFromSuperview] not affecting retain count j o a r Dec 19, 09:51
mlRe: [NSView removeFromSuperview] not affecting retain count Julian Pellico Dec 20, 20:04
mlRe: [NSView removeFromSuperview] not affecting retain count John C. Randolph Dec 20, 20:50
mlRe: [NSView removeFromSuperview] not affecting retain count mmalcolm crawford Dec 20, 21:15
mlRe: [NSView removeFromSuperview] not affecting retain count John C. Randolph Dec 20, 22:26