今天突然發現一個問題,由於對UITableViewCell 的重用機制不是很了解,讓我糾結很久;
用過reloadData時候,會調用cellForRowAtIndexPath方法,但是請看以下2種cellForRowAtIndexPath 的寫法:
寫法A:
1 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 2 { 3 static NSString *brand_region_Cell = @"MyCell"; 4 5 UITableViewCell *celll = [region_table dequeueReusableCellWithIdentifier:MyCell]; 6 7 if (cell == nil) 8 { 9 cell = [[UITableViewCell alloc] initWithStyle: 10 UITableViewCellStyleDefault reuseIdentifier:@"MyCell" ]; 11 12 cell.selectionStyle = UITableViewCellSelectionStyleNone; 13 Obj *obj = [objs objectAtIndex:indexPath.row];
14 cell.textLabel.text = obj.obj_name;
}
return celll;
}
寫法B:
1 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 2 { 3 static NSString *brand_region_Cell = @"brand_region_Cell"; 4 5 UITableViewCell *cell = [region_table dequeueReusableCellWithIdentifier:MyCell]; 6 7 if (cell == nil) 8 { 9 cell = [[UITableViewCell alloc] initWithStyle: 10 UITableViewCellStyleDefault reuseIdentifier:@"MyCell" ]; 11 12 cell.selectionStyle = UITableViewCellSelectionStyleNone; 13 14 } 15 16 Obj *obj = [objs objectAtIndex:indexPath.row]; 17 cell.textLabel.text = obj.obj_name; 18 19 return cell; 20 21 }
大家覺得這兩種寫法有什么不同嗎?
其實,在創建tableView時候,cellForRowAtIndexPath根據section的數量被調用, 在執行reloadData也會調用cellForRowAtIndexPath但是,cell已經存在了,故if (cell == nil){}里面的代碼不會執行,reloadData方法,顧名思義,就是刷新cell的data的,所以cell的data寫在cell判空外面,這是俺犯的一個錯誤,不知道理解的對不對,歡迎指點~
