照着网上的demo写了个UITableView,开始时显示数据完全没问题。实现滚动更新之前尝试拖动它
Like This ——>
这时候就崩溃了!WTF ! 我还没开始实现下拉呢
只能各种查bug
我当时的UITableView实现代码(简化版)大致上是这样的
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellWithIdentifier = @"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellWithIdentifier];
UILabel * title_label; //标题Label
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellWithIdentifier];
CGRect titleLabelF = CGRectMake(20, 3, 300, 20);
title_label = [[UILabel alloc] initWithFrame:titleLabelF];
title_label.font = [UIFont systemFontOfSize:16];//字体大小
[cell addSubview:title_label];
}
[title_label setText:@"1"] ;
//运行到这里就会崩溃
return cell;
}
结果运行到[title_label setText:@”1”] 的时候就是给title_label赋值的时候就崩溃了
查找了很多方法
一开始以为是因为我关闭了arc,结果在项目中启动arc果断就可以了!
但是还是不知道为什么会崩溃。
今天又看了很久发现我代码中有这样一句
if (cell == nil) {
...
title_label = [[UILabel alloc] initWithFrame:titleLabelF];
...
}
我居然天真的在判断语句中初始化对象
解决方法是把上面的代码加在if(cell == nil)外面就可以了
也就是
title_label = [[UILabel alloc] initWithFrame:titleLabelF];
if (cell == nil) {
...
...
}
初步分析的原因是当TableView被拖动到出了页面的时候
title_label对象因为在if语句中被自释放了
所以setText找不到对应的指针导致崩溃
但是为什么启动arc之后就不会崩溃了我也不清楚
具体的内存管理机制还求大神指导~~~
各位朋友记得不要像我一样傻傻的在if语句里分配内存就是了~