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;
這種加載方式在內存充足的情況下看起來是沒問題,一旦內存吃緊的時候問題就暴露出來了!