views:

357

answers:

3

I want to use a UIView heirarchy multiple times (the nib object is a template). Unfortunately, UIView does not conform to <NSCopying> so

[cell.contentView addSubview: [[templEditCellView copy] autorelease]];

does not work.

I wasn't surprised, since I want a deep copy of the view heirarchy.

Currently the view is one of several top-level objects in the nib it is loaded from. Is there a way to reload a single specified top-level object from the nib? Should I split out the view to a single NIB which can be reloaded on demand? Or is there another way to make a deep copy of a view?

Thanks!

A: 

You can't load it directly to the cell's content view, but you can create a class with outlets for the view(s) and load it with

[[NSBundle mainBundle] loadNibNamed:@"TheNib" owner:anObject options:nil];

There is more info around SO and the 'net about loading table view cells from nibs. I really like Bill Dudney's approach but the method described by Jeff LaMarche is easier and great for many situations.

Felixyz
I see an echo between Bill's approach and the one I'm trying. I see that the separate-nib approach is quite workable, just wonder if there are any better. I am severely customizing my UITableCell views!Thanks for the good pointers.
A: 

This seems to be working well at the moment for what I need:

if (! templEditCellView) {
  [[NSBundle mainBundle] loadNibNamed:@"TextEditCellView" owner:self options:nil];
  if (! templEditCellView) {
    abort(); // !!
  }
}
[cell.contentView addSubview: templEditCellView];
templEditCellView = nil;

The table controller is placing the same customized view heirarchy in the content of each cell in this case.

I'd love to see an approach that doesn't multiply nib files if I have lots of different cell customizations (as I might).

+2  A: 

Easiest way to make a deep copy of a view is to archive and unarchive it.

id copyOfAView = 
  [NSUnarchiver unarchiveObjectWithData:
    [NSArchiver archivedDataWithRootObject:aView]]; 

Putting the view in its own nib works too. You can create an NSNib object and reload it as many times as you want.

NSResponder
So I could load my template object graphs (UIViews) once from a nib, archive them to data in a dictionary, and unarchive them individually on demand. I might need to know the performance tradeoff between your simple copy equivalent and my idea of caching the archived data in memory?
If you have the views in question in their own nib files, then my suggestion above is redundant. You can load the nib as many times as you want.
NSResponder