In iOS 6, 2 new methods -registerClass:forCellReuseIdentifier: and -dequeueReusableCellWithIdentifier:forIndexPath: were added to UITableView.
Prior to this, you would write code like the following when you need a UITableView cell instance:
- (UITableViewCell*)tableView:(UITableView*)aTableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
NSString* cellIdentifier = @"MyTableViewCellIdentifier";
UITableViewCell* cell = aTableView.dequeueReusableCellWithIdentifier(cellIdentifier)
if (!cell) {
cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
//config cell
return cell;
}
Starting with iOS 6, you can do this instead:
- (void)viewDidLoad {
[super viewDidLoad];
NSString* cellIdentifier = @"MyTableViewCellIdentifier";
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];
}
- (UITableViewCell*)tableView:(UITableView*)aTableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
NSString* cellIdentifier = @"MyTableViewCellIdentifier";
UITableViewCell* cell = aTableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath:indexPath)
//config cell. cell is always non-nil and the cell will have the correct height as returned by -tableView:heightForRowAtIndexPath:.
return cell;
}
-dequeueReusableCellWithIdentifier:forIndexPath: always return a valid cell so we can skip the nil check. The cell will also have the correct height as returned by -tableView.heightForRowAtIndexPath:
Note that using this, all cells created will have the style UITableViewCellStyleDefault unless we use a UITableViewCell subclass.
转载地址:http://tinyletter.com/iosdev/letters/ios-dev-tip-50-uitableview-registerclass-forcellreuseidentifier