Reputation: 29518
I created a UITableViewCell subclass. In the HomeViewController class that currently uses it, I do this:
@interface: (for HomeViewController)
@property (nonatomic, assign) IBOutlet UITableViewCell *customCell;
@implementation:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CustomTableViewCellIdentifier = @"CustomTableViewCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomTableViewCellIdentifier];
if (cell == nil) {
UINib *cellNib = [UINib nibWithNibName:@"CustomTableViewCell" bundle:nil];
[cellNib instantiateWithOwner:self options:nil];
cell = self.customCell;
self.customCell = nil;
}
NSUInteger row = [indexPath row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
In the CustomTableViewCell.xib, my File's Owner is HomeViewController and I connect the outlet from File's Owner to the CustomTableViewCell. All of that works fine.
Now I want to have another subclass of UIViewController called DetailViewController to use this cell also. My File's Owner object is already used. I'm not super familiar with creating other objects in order to reuse this cell. Can someone explain what I need to do in this scenario? Thanks.
Upvotes: 1
Views: 723
Reputation: 385998
First, don't create a UINib
object every time. Create it once and reuse it. It will run much faster.
Second, it looks like the only property of File's Owner that you're wiring up is customCell
. If that's all you need, it would be simpler not to wire up a connection at all. Instead, make sure the cell is the first or only top-level object in the nib (by making it the first top-level object in the Objects section of the nib outline). Then you can access it like this:
+ (UINib *)myCellNib {
static UINib *nib;
static dispatch_once_t once;
dispatch_once(&once, ^{
nib = [UINib nibWithNibName:@"CustomTableViewCell" bundle:nil];
});
return nib;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CustomTableViewCellIdentifier = @"CustomTableViewCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomTableViewCellIdentifier];
if (cell == nil) {
NSArray *topLevelNibObjects = [self.class.myCellNib instantiateWithOwner:nil options:nil];
cell = [topLevelNibObjects objectAtIndex:0];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
Upvotes: 4