ios 变量报EXC_BAD_ACCESS错误
大家讲道理
大家讲道理 2017-04-17 11:24:15
[iOS讨论组]

做的是一个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错误信息
这个错误个人认为是对一个已经释放的对象进行操作所产生的,但是不知道错误发生在什么地方

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(3)
迷茫

看起来是你的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) {
    ;;
}
PHP中文网

oldIndex第一次使用的时候,还光声明了,没初始化吧,假如默认没走“indexPath.row==2”分支的话

PHPz

为什么不用ARC呢?完全可以避免这种问题

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号