Osobiście uważam, że oba sugerowane tutoriale mają dużą wadę, jeśli chodzi o reuseIdentifier
. Jeśli zapomnisz go przypisać w konstruktorze interfejsów lub źle przeliterować, ładujesz stalówkę za każdym razem, gdy zostanie wywołana cellForRowAtIndexPath
.
Jeff LaMarche pisze o tym i jak to naprawić w tym blog post. Oprócz reuseIdentifier
używa tego samego podejścia, co w dokumentacji Apple na Loading Custom Table-View Cells From Nib Files.
Po przeczytaniu wszystkich tych artykułów wymyśliłem następujący kod:
Edit: Jeśli są kierowane iOS 5.0 i wyższe będziesz chciał trzymać się Duane Fields' answer
@interface CustomCellWithXib : UITableViewCell
+ (NSString *)reuseIdentifier;
- (id)initWithOwner:(id)owner;
@end
@implementation CustomCellWithXib
+ (UINib*)nib
{
// singleton implementation to get a UINib object
static dispatch_once_t pred = 0;
__strong static UINib* _sharedNibObject = nil;
dispatch_once(&pred, ^{
_sharedNibObject = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
});
return _sharedNibObject;
}
- (NSString *)reuseIdentifier
{
return [[self class] reuseIdentifier];
}
+ (NSString *)reuseIdentifier
{
// return any identifier you like, in this case the class name
return NSStringFromClass([self class]);
}
- (id)initWithOwner:(id)owner
{
return [[[[self class] nib] instantiateWithOwner:owner options:nil] objectAtIndex:0];
}
@end
UINib (dostępny w iOS 4.0 i późniejszych) jest używany tutaj jako singleton, ponieważ chociaż używa się reuseIdentifier
, komórka nadal jest ponownie inicjowana około 10 razy. Teraz cellForRowAtIndexPath
wygląda następująco:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCellWithXib *cell = [tableView dequeueReusableCellWithIdentifier:[CustomCellWithXib reuseIdentifier]];
if (cell == nil) {
cell = [[CustomCellWithXib alloc] initWithOwner:self];
}
// do additional cell configuration
return cell;
}
Moim zdaniem jest to najlepszy sposób. Dziękuję za to. Gdyby to był mój temat, oznaczałbym to jako odpowiedź. –