【问题标题】:TitleForHeaderInSection throwing EXC_BAD_ACCESSTitleForHeaderInSection 抛出 EXC_BAD_ACCESS
【发布时间】:2011-11-15 18:16:37
【问题描述】:

我正在尝试在我的 iPhone 应用程序中创建一个通用的 UITableView。 我有一个UITableView,它通过 SELECT 查询循环使用数组填充数据。 我将数据添加到我的数组中并在cellForRowAtIndexPath: 中填充数组。 我使用该数组获取节标题,并使用排序方法将节标题放入Array1

我想让titleForHeaderInSection: 工作,将第 0 节设置为静态标题名称,将第 1 节和稍后变为通用名称,这意味着标题名称将来自 Array1

我不确定如何创建该逻辑,因为应用程序总是使用下面的代码抛出 EXC_BAD_ACCESS

我的逻辑:我将数组的计数保存在int 中,并查看该值是否大于0。如果是,我为和objectAtIndex:0 添加节标题,否则我使用静态的。但是当计数达到 2 时,对于第 2 节和objectAtIndex:1,它会中断并抛出 EXC_BAD_ACCESS。

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    int value = [[self Array1] count];
    if(section == 0)
        return @"Countries";

    if (value > 0) {
        if (section == value){
        return [[self Array1] objectAtIndex:section - 1];
    }
    }   
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    int count = [[self Array1] count];
    return count + 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section      
{
    int value = [[self Array1] count];
    if (section == 0) {
    return [self.Array count];
    }

    if (value > 0) {
        if (section == [[self Array1] count])  {
            NSString *initialLetter = [[self Array1] objectAtIndex:section - 1];

            // get the array of elements that begin with that letter
            NSArray *elementsWithInitialLetter = [self elementsWithInitialLetter:initialLetter];

            // return the count
            return [elementsWithInitialLetter count];
        }
    }

}

【问题讨论】:

  • 将环境变量 NSZombieEnabled 设置为 YES 并测试您的代码。完成后在此处发布调试日志。
  • 但是,我的逻辑正确吗?我不确定这是否有效。

标签: objective-c cocoa-touch memory-management uitableview


【解决方案1】:

看起来您只是缺少支持 Array1 方法的 iVar 上的保留。将数组声明为属性:

@property (nonatomic, retain) NSArray* datastore;

然后在这个方法中缓存你在Array1方法中引用的值(可能在viewDidLoad中)。

self.datastore = [self Array1];

然后将所有剩余的对[self Array1] 的引用替换为self.datastore。构建运行,看看它是否仍然崩溃。 (不要忘记在你的 dealloc 中设置self.datastore = nil

【讨论】:

  • @Change 消息发送到解除分配的实例;使用 stacktrace 更新您的问题(gdb > bt 是命令)并将已释放的实例消息发送到哪个。尽可能多地提供调试信息,帮助您快速获得答案并点赞。
猜你喜欢
  • 2014-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多