开发者社区> 问答> 正文

ios 变量报EXC_BAD_ACCESS错误

做的是一个UITableView单选的简单Demo,但是在行选择的时候出现了EXC_BAD_ACCESS错误
先上代码:
UITableViewSingleChoiceViewController.h

@interface UITableViewSingleChoiceViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,retain)NSIndexPath *oldIndex;
@end
UITableViewSingleChoiceViewController.m

#import "UITableViewSingleChoiceViewController.h"
#import "Cell.h"  //自定义的一个UITableViewCell

@interface UITableViewSingleChoiceViewController ()

@end

@implementation UITableViewSingleChoiceViewController{
    UITableView *table;
}
@synthesize oldIndex;

-(void)viewDidLoad
{
    [super viewDidLoad];
    table=[[UITableView alloc]initWithFrame:self.view.bounds];
    table.delegate=self;
    table.dataSource=self;
    [self.view addSubview:table];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *nib=[[NSBundle mainBundle]loadNibNamed:@"Cell" owner:self options:nil];
    Cell *cell=[nib objectAtIndex:0];
    if(indexPath.row==2){
     cell.thumbnail.image=[UIImage imageNamed:@"帐号切换"];
        oldIndex=indexPath;
    }else{
        cell.thumbnail.image=[UIImage imageNamed:@"帐号切换2"];
    }
    cell.label.text=[NSString stringWithFormat:@"tableview cell - %d",indexPath.row+1];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath isEqual:oldIndex]){
        NSLog(@"行选择没有变");
    }else{
        Cell *newCell = (Cell *)[tableView cellForRowAtIndexPath:indexPath];
        newCell.thumbnail.image=[UIImage imageNamed:@"帐号切换"];

        Cell *oldCell = (Cell *)[tableView cellForRowAtIndexPath:oldIndex];
        oldCell.thumbnail.image=[UIImage imageNamed:@"帐号切换2"];
        oldIndex=indexPath;
    }
}

@end

在 tableView didSelectRowAtIndexPath方法中的第一行就出现了EXC_BAD_ACCESS错误信息
screenshot

展开
收起
a123456678 2016-07-20 11:51:11 2633 0
1 条回答
写回答
取消 提交回答
  • 看起来是你的oldIndex出了问题。两个建议

    1,用copy来管理oldIndex,并且在调用时使用 self.

    @property (nonatomic, copy) NSIndexPath *oldIndex;
    NSLog(@"section: %d, row: %d", self.oldIndex.section, self.oldIndex.row);
    2,不直接比较NSIndexPath对象

    if (indexPath.section == self.oldIndex.section

      && indexPath.row == self.oldIndex.row) {
    ;;

    }

    2019-07-17 19:58:46
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
手淘iOS性能优化探索 立即下载
From Java/Android to Swift iOS 立即下载
深入剖析iOS性能优化 立即下载