您的位置:首页 > 其它

-tableView: cellForRowAtIndexPath:方法不执行问题

2014-11-18 16:00 453 查看
今天在学习UItableView 的时候,定义了一个属性

@property (weak, nonatomic) NSMutableArray *dataList;


在ViewDidLoad方法方法中用一下方法实例化

_dataList = [NSMutableArray arrayWithCapacity:20];

for (NSInteger i = 0; i < 20; i++)

{

Book *book = [[Book alloc]init];

NSString *string = [NSString stringWithFormat:@"iOS进阶(%ld)", i];

[book setBookName:string];

[book setPrice:98.98];

[_dataList addObject:book];

}


然后实现UItableViewDataSource代理方式

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * CellIdentifier = @"bookCell";
BookCell *bookCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (bookCell == nil)
{
bookCell = [[BookCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
NSBundle *bundle = [NSBundle mainBundle];
NSArray *array = [bundle loadNibNamed:@"BookCell" owner:nil options:nil];
bookCell = [array lastObject];
}

Book *book = _dataList[indexPath.row];
bookCell.bookPrice.text = book.bookPrice;
bookCell.bookName.text = book.bookName;

return bookCell;

}


运行以后没有任何数据,也没有错误,跟踪调试后发现-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法没有执行,再继续跟踪,发现

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
2 {
3 return _dataList.count;
4 }

这个方法的返回值是0,即使 _dataList.count是0,为什么是0,原来在定义的时候把 _dataList 属性写成了weak,所以就没有retain,要写成strong。由于- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 的返回值是0,所以就不会调用-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 了。

关于weak和strong看这篇文章http://www.2cto.com/kf/201303/192824.html;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐