Can someone please school me on the proper way to load a view hierarchy from a nib file. I am using the loaded view as a template to stamp out a family of views and the current approach I am using is subtly broken. I don’t appear to be copy-ing or retain-ing when I should be. Here’s the relevant code:
// pageSet is a list of view tag numbers I'll be using
for (NSNumber *n in pageSet) {
NSUInteger viewTag = [n integerValue];
// Ingest the nib. Should there be a copy or retain here?
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"RandomStripe" owner:self options:nil];
// Pull the view from the nib. Should there be a copy or retain here?
MyView *view = (MyView *)[topLevelObjects objectAtIndex:0];
// The view has a label as it's subview
UILabel *pageNumberLabel = [view.subviews objectAtIndex:0];
pageNumberLabel.text = [NSString stringWithFormat:@"%d", viewTag];
CGFloat xOffset = ((float) viewTag) * self.scrollView.bounds.size.width;
view.frame = CGRectMake(xOffset, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height);
view.tag = viewTag;
// Insert the view as a child of my containerView
[self.containerView addSubview:view];
} // for (pageSet)
This has be making my head hurt for while now?
Cheers,
Doug
If you use IBOutlets from within Interface Builder back to your code, things would be a little easier. That way as soon as you try to access the UIView outlet you have set up, it gets loaded, with all its children, and then the UIView’s initWithCoder will get called (useful if you have subclassed it).
Otherwise, I do this:
(With an IBOutlet for numberView, I just go ahead and start using numberView instead of the code above)
In both conditions, all the subviews – the children – of numberView will get loaded at the same time. If I needed to access a label or button I would do an IBOutlet for those too so I won’t have to traverse the view hierarchy looking for them.