iOS UITableView的復(fù)用機制簡析




////? ViewController.m

//? D1-SingleGroupTableView//

//? Created by? CE? on 16/4/15.

//? Copyright ? 2016年 CE. All rights reserved.

//#import "ViewController.h"@interface ViewController ()//數(shù)據(jù)源

@property NSMutableArray *dataSource;

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

//創(chuàng)建數(shù)據(jù)

[self createDataSource];

//創(chuàng)建表格視圖

[self createTableView];

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

- (BOOL)prefersStatusBarHidden {

return YES;

}

- (void)createDataSource {

self.dataSource = [NSMutableArray array];

for (NSUInteger i=0; i<50; i++) {

NSString *str = [NSString stringWithFormat:@"科密%.2lu號", i+1];

[self.dataSource addObject:str];

}

}

- (void)createTableView {

UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds];

//設(shè)置數(shù)據(jù)源代理

tableView.dataSource = self;

//注冊cell類型以及復(fù)用標(biāo)識

[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellId"];

[self.view addSubview:tableView];

}

#pragma mark - UITableViewDataSource

//有多少行

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return self.dataSource.count;

}

//哪一組的哪一行

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

//面試

//表格視圖內(nèi)部維護了一個cell的復(fù)用隊列,每次需要新的cell時,可以先從隊列中根據(jù)復(fù)用標(biāo)識尋找是否有空閑的cell,若有則直接出列使用無需創(chuàng)建新的;若沒有可用cell則需要創(chuàng)建新的。

//表格視圖上的cell離開顯示區(qū)域就會自動放入復(fù)用隊列

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];

#if 0

//若不想判斷,則前面需要注冊cell類型及同復(fù)用標(biāo)識

if (!cell) {

static int count = 0;

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellId"];

count++;

printf("創(chuàng)建cell%d\n", count);

}

#endif

cell.textLabel.text=self.dataSource[indexPath.row];

return cell;

}

@end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容