dequeueReusableCellWithIdentifier
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
return cell;
}
static NSString *CellIdentifier = @"Cell";
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
이 코드 한줄로 할당한 셀(cell)을 찾아(deque) 재활용(reuse)하는겁니다
이제 이 함수가 이해 가시나요?
모르셨던분들은 메모리가 크지않는 아이폰에서 이 함수의 존재가 달리 보이실겁니다.
이제 제가 이야기하고자 하는 것의 본론으로 들어가보죠.
많은 분들이(심지어 몇몇 기본서에서도) 커스템셀의 사용법을 알려줄 때(xib생성방식으로 할 때)
CustomTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellName];
if (cell == nil) {
NSArray* nib= [[NSBundle mainBundle] loadNibNamed:cellName owner:self options:nil];
cell = [nib objectAtIndex:0];
}
이렇게만 설명하고 끝이납니다.
자 우리는 이때 의심을 한번 가져봐야 합니다. 과연 위의 코드로 셀을 생성할 때 저
dequeueReusableCellWithIdentifier
로 리턴된값이 항상 nil일 수도 있지않을까 라고 말이죠.
근거는 간단합니다.
커스텀이 아닐때와 비교해보면 말이죠.
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]
NSArray* nib= [[NSBundle mainBundle] loadNibNamed:cellName owner:self options:nil];
cell = [nib objectAtIndex:0];
자 이제 의심이 가기 시작하시나요?
눈치채셨겠지만 기본 셀은 reuseIdentifier라는 인자로 구분자를 넘겨줌니다.
하지만 커스템셀생성시엔 전혀 그런 과정이 없죠.
따라서 tableview에는 셀이 어떠한 Identifier로 큐잉이 되지 않는거죠.
자. 그렇다면 해결법은 무엇일까요??
간단합니다. 저 identifier를 적어주면 되는것이지요.
저것을 적어주지않고 그냥 해서 스크롤 내릴때마다 메모리에 셀이 계속해서 올라가게 되기 때문이죠.