dequeueReusableCellWithIdentifier vs dequeueReusableCellWithIdentifier : forIndexPath

Deft_MKJing宓珂璟發表於2017-09-30

StackOverFlow連結

老外的原文問題連結

方法名介紹

- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;  // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.
- (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0); // newer dequeue method guarantees a cell is returned and resized properly, assuming identifier is registered

區別

這兩個方法都是在tableView:cellForRowAtIndexPath 這個方法裡面獲取cell用的
1.對於dequeueReusableCellWithIdentifier:forIndexPath
如果沒有給複用的id註冊一個class或者nib的話,那麼程式就會crash
2.對於dequeueReusableCellWithIdentifier 如果沒有給複用id註冊一個class或者nib的話,那麼就會返回nil

因此對於老的方法

UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];   
// 需要手動判斷是否為nil
if (cell == nil) {
    //建立cell 
   cell  = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}

對於新的方法
dequeueReusableCellWithIdentifier:forIndexPath

//第一步 註冊  一個通過xib 一個通過class。隨便選一個
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0);  
- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);

//第二步 
// 不需要判斷cell是否為nil,該新方法如果找不到cell,會自動呼叫
// initWithStyle:withReuseableCellIdentifier 建立一個新的
// 因此,必定不為空
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];

// 那麼引數indexpath有什麼用?
// 因為在返回cell之前,會呼叫委託ableView:heightForRowAtIndexPath來確定cell尺寸(如果已經定義該函式)。

1.The most important difference is that the forIndexPath: version asserts (crashes) if you didn’t register a class or nib for the identifier. The older (non-forIndexPath:) version returns nil in that case.

2.the (then-new) forIndexPath: version starting around 8m30s. It says that “you will always get an initialized cell” (without mentioning that it will crash if you didn’t register a class or nib).

3.The video also says that “it will be the right size for that index path”. Presumably this means that it will set the cell’s size before returning it, by looking at the table view’s own width and calling your delegate’s tableView:heightForRowAtIndexPath: method (if defined). This is why it needs the index path.

相關文章