static NSString * Identifier = @"pastRecordsCell";
BOOL nibsRegistered = NO;
if (!nibsRegistered) {
UINib * nib = [UINib nibWithNibName:NSStringFromClass([ZSPastRecordsCell class]) bundle:nil];
[tableView registerNib:nib forCellReuseIdentifier:Identifier];
nibsRegistered = YES;
}
ZSPastRecordsCell * pastRecordsCell = (ZSPastRecordsCell *)[tableView dequeueReusableCellWithIdentifier:Identifier];
pastRecordsCell.selectionStyle = UITableViewCellSelectionStyleNone;
[pastRecordsCell configPastRecordsCell:self.dataArray[indexPath.row]];
return pastRecordsCell;
除此之外,還需在XIB檔案中設定與代碼中一樣的Identifier。
注意:UINib是iOS4以後出來的類,與MAC上的NSNib類相似。就是對頻繁使用的NIB檔案的加載。當第一次從硬碟加載NIB是,它在内容中緩存NIB檔案對象,之後加載的XIB檔案就會從記憶體中拷貝出來,進而避免了較慢的硬碟通路。使用UINib最明顯的地方就是在需要每次建立新Cell時從NIB檔案中加載Cell的UITableViewController中。UINib的優勢就是在不用大量修改代碼的情況下獲得性能的改進。apple曾宣稱可以在加載UINib檔案時提供2倍速度的提升。其原理簡單講就是,利用緩存機制避免頻繁的從硬碟中加載XIB檔案,這在大資料量的時候尤為突出。
另一種XIB代碼重用的示例:
static NSString * Identifier = @"pastRecordsCell";
ZSPastRecordsCell * cell ;
cell = (ZSPastRecordsCell *)[tableView dequeueReusableCellWithIdentifier:Identifier];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([ZSPastRecordsCell class]) owner:self options:nil] lastObject];
}
return cell;
這種加載方式在記憶體充足的情況下看起來是沒問題,一旦記憶體吃緊的時候問題就暴露出來了!