2

For some reason, using loadNibNamed: is leaving me with a memory leak.

Let's say I have the interfaces:

@interface Step : UIViewController
{
  IBOutlet UIView *keyPadPopupView;
}
@property (nonatomic, assign) IBOutlet UIView *keyPadPopupView;

In Step:

@synthesize keyPadPopupView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
  {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) 
    {
        [[NSBundle mainBundle] loadNibNamed:@"customNumberKeypad" owner:self options:nil];
        [self.view addSubview:keyPadPopupView];
        [keyPadPopupView release];
    }
    return self;
  }

- (void) dealloc
{
    NSLog(@"dealloc........%@", [self class]);
    [super dealloc];
}

I perform the init using:

Step *step = [[Step alloc] initWithNibName:@"StepXib" bundle:nil];
[step release]; 

I can't seem to figure out why the dealloc method is never called. Inside the Xib, the file's owner is Step, and the keyPadPopupView is connected in IB.

Is there something I'm missing?

Thanks!

mmilo
  • 806
  • 11
  • 18
  • So commenting out the inner block of initWithNibName causes dealloc to be called as expected? – Seamus Campbell Aug 04 '10 at 02:20
  • I'm a little perplexed as to why you're releasing keyPadPopupView right away, rather than in dealloc as is customary for object variables... – Seamus Campbell Aug 04 '10 at 02:21
  • Correct, commenting out the inner block causes dealloc to be called as expected. I'm releasing keyPadPopupView because the dealloc isn't being called regardless. – mmilo Aug 04 '10 at 02:30
  • how is `keyPadPopupView` being assigned to anything? – jowie Aug 23 '13 at 10:22

1 Answers1

2

In iOS connecting an IBOutlet causes the object to be retained (unlike OS X). Adding a view to a subview causes it to be retained. So...

Load from nib - +1 (1)

Add as subview - +1 (2)

release - -1 (1)

You still have an outstanding retain.

Is viewDidUnload being called? Normally in there you release all the retained subviews.

vagrant
  • 868
  • 1
  • 9
  • 23
  • 1
    Even if the outlet is an `assign` property? –  Jun 20 '11 at 01:13
  • 2
    Yes. It is part of the nib loading. OS X does not do a retain so this bit me early on in iOS development. Remember, the nib filling in your outlets is not really aware of your properties. You can specifiy the IBOutlet on the ivar and have no property defined and it works. (That is how it was before properties were introduced) – vagrant Jul 19 '11 at 19:16
  • Can you please add reference to documentation to back this up? Sounds like you know, I'm just looking for official confirmation. Thanks! – Oded Ben Dov Jun 07 '12 at 16:52
  • 1
    http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/LoadingResources/CocoaNibs/CocoaNibs.html Look at the "Legacy Patterns" section. It has changed since I first came across it, but it makes it clear. – vagrant Jun 18 '12 at 20:29