【问题标题】:UITableView reloadData EXC_BAD_ACESS code=2UITableView reloadData EXC_BAD_ACESS 代码=2
【发布时间】:2013-09-27 03:40:49
【问题描述】:

我有这个加载 UITableView 的代码:

- (int)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.peopleTableView)
        return [self.people count];
    else
        return [[[self.scheduleDays objectAtIndex:self.dayInt] periods] count];
}

- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.peopleTableView)
        return [[self.people objectAtIndex:section] count];
    else
        return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (tableView == self.peopleTableView)
        return [self.headers objectAtIndex:section];
    else
        return [NSString stringWithFormat:@"%@ - %@", [[[[self.scheduleDays objectAtIndex:self.dayInt] periods] objectAtIndex:section] startTime], [[[[self.scheduleDays objectAtIndex:self.dayInt] periods] objectAtIndex:section] endTime]];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.headers;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return index;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.peopleTableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        if (cell == nil)
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];

        Person *person = [[self.people objectAtIndex:[indexPath section]] objectAtIndex:[indexPath row]];
        [[cell textLabel] setText:[NSString stringWithFormat:@"%@ %@", [person firstName], [person lastName]]];

        return cell;
    } else {
        ScheduleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

        if (cell == nil) {
            cell = [[ScheduleTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }

        Period *period = [[[[[[self appDelegate] user] scheduleDays] objectAtIndex:self.dayInt] periods] objectAtIndex:[indexPath section]];

        [[cell mainLabel] setText:[period desc]];
        [[cell subtitleLabel1] setText:[period teacher]];
        [[cell subtitleLabel2] setText:[period roomLocation]];

        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.peopleTableView) {
        self.currentViewedPerson = [[self.people objectAtIndex:[indexPath section]] objectAtIndex:[indexPath row]];
        [self loadPerson:self.currentViewedPerson];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.scheduleTable)
        return 70;
    else
        return 44;
}

我使用方法调用[_tableView reloadData] 来加载数据。第一次工作正常,但第二次失败,EXC_BAD_ACCESS code=2。为什么?

编辑:

似乎错误来自对

的调用
#0  0x01b8c2a3 in TComponentFont::GetMinSideBearing(CGAffineTransform const&, bool) const ()

或致电

我希望这会有所帮助。

编辑:

NSZombies 也没有帮助。在 Xcode 中运行它(使用 NSZombies)我得到相同的错误,没有输出,使用僵尸配置文件对其进行分析,它没有任何消息,应用程序只是崩溃。

编辑:

此错误来自部分标题,因为当我注释掉这些部分时,我不再收到错误。我的章节标题实现有什么不正确的地方?

编辑:

这就是_headers 在 DirectoryViewController.h 中的声明方式:

@property (strong, nonatomic) NSMutableArray *headers;

标题是如何填充的(可能不是所有必要的,但是...):

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    if (parser == self.peopleParser) {
        if ([elementName isEqualToString:@"People"]) {
            self.people = [NSMutableArray array];
            self.headers = [NSMutableArray array];
        } else if ([elementName isEqualToString:@"Person"]) {
            self.currentPerson = [Person new];
            [self.currentPerson setPersonID:[attributeDict objectForKey:@"id"]];
        }
    } else if (parser == self.scheduleParser) {
        if ([elementName isEqualToString:@"Schedule"])
            self.scheduleDays = [NSMutableArray array];
        else if ([elementName isEqualToString:@"Day"]) {
            NSEntityDescription *entity = [NSEntityDescription entityForName:@"ScheduleDay" inManagedObjectContext:[[self appDelegate] managedObjectContext]];
            self.currentDay = [[ScheduleDay alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
        } else if ([elementName isEqualToString:@"Course"]) {
            NSEntityDescription *entity = [NSEntityDescription entityForName:@"Period" inManagedObjectContext:[[self appDelegate] managedObjectContext]];
            self.currentPeriod = [[Period alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
        }
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    self.currentString = string;
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if (parser == self.peopleParser) {
        if ([elementName isEqualToString:@"People"])
            self.currentLetter = @"";
        else if ([elementName isEqualToString:@"Person"]) {
            if ([self.currentLetter isEqualToString:[[[self.currentPerson lastName] substringToIndex:1] uppercaseString]])
                [[self.people lastObject] addObject:self.currentPerson];
            else {
                [self.people addObject:[NSMutableArray array]];
                [self.headers addObject:[[[self.currentPerson lastName] substringToIndex:1] uppercaseString]];
                self.currentLetter = [[[self.currentPerson lastName] substringToIndex:1] uppercaseString];
                [[self.people lastObject] addObject:self.currentPerson];
            }
        } else if ([elementName isEqualToString:@"Last"])
            [self.currentPerson setLastName:self.currentString];
        else if ([elementName isEqualToString:@"First"])
            [self.currentPerson setFirstName:self.currentString];
        else if ([elementName isEqualToString:@"EmailAddress"])
            [self.currentPerson setEmail:self.currentString];
        else if ([elementName isEqualToString:@"PhoneCell"])
            [self.currentPerson setCellPhone:self.currentString];
        else if ([elementName isEqualToString:@"PhoneHome"])
            [self.currentPerson setHomePhone:self.currentString];
        else if ([elementName isEqualToString:@"GradYear"])
            [self.currentPerson setGradYear:self.currentString];
        else if ([elementName isEqualToString:@"StudentGrade"])
            [self.currentPerson setGrade:self.currentString];
        else if ([elementName isEqualToString:@"Street1"])
            [self.currentPerson setStreet1:self.currentString];
        else if ([elementName isEqualToString:@"Street2"])
            [self.currentPerson setStreet2:self.currentString];
        else if ([elementName isEqualToString:@"City"])
            [self.currentPerson setCity:self.currentString];
        else if ([elementName isEqualToString:@"State"])
            [self.currentPerson setState:self.currentString];
        else if ([elementName isEqualToString:@"Zip"])
            [self.currentPerson setZip:self.currentString];
    } else if (parser == self.scheduleParser) {
        if ([elementName isEqualToString:@"Course"])
            [self.currentPeriod setDay:self.currentDay];
        else if ([elementName isEqualToString:@"Day"])
            [self.scheduleDays addObject:self.currentDay];
        else if ([elementName isEqualToString:@"StartTime"])
            [self.currentPeriod setStartTime:self.currentString];
        else if ([elementName isEqualToString:@"EndTime"])
            [self.currentPeriod setEndTime:self.currentString];
        else if ([elementName isEqualToString:@"Description"])
            [self.currentPeriod setDesc:self.currentString];
        else if ([elementName isEqualToString:@"Location"])
            [self.currentPeriod setRoomLocation:self.currentString];
        else if ([elementName isEqualToString:@"Teacher"])
            [self.currentPeriod setTeacher:self.currentString];
    }
    self.currentString = @"";
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    if ([parseError code] == 5) {
        self.people = [NSMutableArray array];
        self.headers = [NSMutableArray array];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:[parseError description] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
    }
}

编辑:

reloadData 的调用位置:

- (void)search {
    NSString *urlString = [LINK SETUP CODE GOES HERE]

    self.peopleParser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]];
    self.peopleParser.delegate = self;
    if ([self.peopleParser parse] && [self.people count] > 0) {
        [self.peopleTableView reloadData];
        [self.peopleTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        [self.view addSubview:self.peopleView];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Results!" message:@"Your search returned no results. Try broadening your search." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
    }
    [self.activityIndicator stopAnimating];
    self.activityIndicator.hidden = YES;
}

【问题讨论】:

  • 该错误通常是由于尝试访问已释放的对象而发生的。您应该确保所有对象都有指向它们的强指针(例如 _people 和 _headers)。
  • 你是如何分配_people
  • @samfisher _people = [NSMutableArray new];
  • @rdelmar 所有对象都有强指针
  • @samfisher 我也试过_people = [NSMutableArray array],但我得到了同样的错误

标签: ios objective-c uitableview automatic-ref-counting exc-bad-access


【解决方案1】:

为避免内存问题,您应该创建对象并使用属性访问器方法引用您的对象。

例如,您为headers 可变数组声明属性:

@property (strong, nonatomic) NSMutableArray *headers;

那么你应该这样创建你的数组:

 self.headers = [NSMutableArray array];

并以这种方式引用您的数组:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [self.headers objectAtIndex:section];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.headers;
}

使用这种语法,您可以为headers 属性调用setter 和getter 方法(这些方法由Xcode 自动生成)。

在非 ARC 环境中,为 (retain, nonatomic) 属性调用这些方法是等效的(retainstrong 的模拟):

- (NSMutableArray *)headers {

  return _headers;
 }

- (void)setHeaders:(NSMutableArray *)headers {

    [_headers autorelease];
    _headers = [headers retain];
}

如果您在 ARC 环境中使用 self. 表示法,将自动跟踪对象的引用计数。

您可以找到更多关于属性here的信息。

编辑:

这似乎是框架中的一个错误。检查这个answer

【讨论】:

  • 最后一个半相关的问题。通过 object.var 和 [object var]/[object setVar] 访问和设置对象有区别吗?还是两者都调用相同的方法?
  • 两种变体是相等的。只是新旧符号样式。
  • 看来我批准你过早地回答了。我希望在我给你 50 之后你仍然有兴趣:)。我试过一次,它似乎工作,但现在问题又出现了。我将编辑问题中的代码以反映我现在拥有的内容。
  • 尝试设置异常断点以获取有关应用程序崩溃位置的更多信息。 developer.apple.com/library/ios/recipes/… 另外请提供更多信息,说明您在何时何地调用 reloadData。
  • 这似乎是框架中的一个错误。检查这个答案stackoverflow.com/a/19010375/1158590
【解决方案2】:

第二个是因为自动释放,你应该使用 NSLog() 检查值,然后你可以很容易地找到解决方案。在不同的阶段或以不同的方法获取每个值

【讨论】:

  • NSLogging 时一切正常。我现在在返回 sectionIndexTitles 数组期间或之后得到 code=2 而不是 code=1。所以我需要先将 NSMutableArray 转换为 NSArray ,因为我认为它会自动转换,为什么它会在第一次而不是第二次起作用?
【解决方案3】:

在没有看到更多代码的情况下,我的猜测是,虽然字符串对于标头数组是等效的,但您没有在 sectionForIndexTitle 中正确比较它们。

请记住,indexOfObject 仅在指向字符串的指针完全相同时才有效。拥有两个具有相同值的字符串并不一定足够。

为了安全你可以试试:

for (int i = 0; i < [_headers count]; ++i)
{
    if ([_headers[i] isEqualToString title])
    {
        return i;
    }
}
// error handling belongs here

但同样,这是一个猜测,因为我们对 _headers 的构造方式或您的代码中发生的其他情况没有清楚的了解。

【讨论】:

  • 请看我最后一次关于主要问题的cmets。
  • 返回 sectionForSectionIndexTitle 的索引是不正确的行为,除非您 100% 确定所有字母都包含在您的部分列表中。相反,您需要计算最近的相似部分。例如,如果您的标头包含“A”、“C”和“F”,则当您传递“D”时,您需要返回 1 或 2。
  • 此索引列表是标题列表,因此可以完成。
【解决方案4】:

我认为这次崩溃是由于 TableView 对象、'_people' 数组或 '_headers' 数组的自动释放造成的。您要做的第一件事是记录其值以检查它是否是已发布的对象。 如果是这样,您可以使用

  [_people retain]; 

  [_headers retain];

 [tableviewObject retain]; 

为了避免自动释放。

【讨论】:

  • retain 方法已弃用,请提供未弃用的代码。
  • 还有究竟是什么导致了这个问题以及为什么自动释放在这种情况下不起作用。
猜你喜欢
  • 1970-01-01
  • 2011-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-04
  • 2011-11-24
  • 2019-06-12
相关资源
最近更新 更多