【问题标题】:Getting a memory address instead of the object at that address获取内存地址而不是该地址处的对象
【发布时间】:2015-03-26 14:39:10
【问题描述】:

我正在编写一个程序,其中包含一个包含多个对象的数组。然后,我从该数组中获取特定对象并将它们的索引(来自array1)作为NSNumbers 存储在另一个数组中。现在,我试图通过在表视图中将索引从 array2 中拉出来在项目中稍后引用来自 array1 的对象,但我不断收到一个错误,表明我正在获取对象的内存地址而不是对象本身。要遵循的代码:

self.indexArray = [NSMutableArray new];
    for (Item *item in array1){
        if (item.ID == comparedItem.ID){
            NSUInteger num = [array1 indexOfObject:item];
            NSNumber *numval = [NSNumber numberWithInteger:num];
            [self.indexArray addObject:numval];
        }
    }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = (EditItemTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"quantityCell"];
int indexNum = [[self.indexArray objectAtIndex:(indexPath.row-1)] intValue];
NSString *descString = [NSString stringWithFormat:@"%@ %@ - %@",[[array1 objectAtIndex:indexNum]desc1],[[array1 objectAtIndex:indexNum]desc2],indexNum];
return cell;
}

所以我在线上遇到了一个错误:int indexNum = [[self.indexArray objectAtIndex:(indexPath.row-1)] intValue];,通常是这样的:*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 4294967295 beyond bounds [0 .. 2]'。这是假设我在运行上面的代码之前向数组中添加了 3 个对象(因此是 0 .. 2)。我假设 4294967295 是一个内存地址。有没有人知道我如何才能获得对象本身?

谢谢!

【问题讨论】:

  • 如果在该行代码之前记录 indexPath 或 indexPath.row 的值会发生什么?
  • 4294967295 是 -1,表示为无符号 int32。在这种情况下,它代表indexPath.row-1 == -1 或indexPath.row == 0。
  • 貌似indexPath.row为0,减1为整数下溢。
  • IndexPath.row 给了我很好的数据(0、1、2,基于迭代)。记录 [self.indexArray objectAtIndex:2] 之类的东西,我在其中硬编码 objectAtIndex 而不是使用 indexPath.row-1 引用它,这也给了我一个有效的答案。
  • 哦。好吧,看来我是个彻头彻尾的白痴。哇。我对自己的愚蠢感到惊讶。 Ian 或Nobody,谁先发布答案,我会得到一个漂亮的绿色复选标记!

标签: ios objective-c cocoa-touch pointers memory-management


【解决方案1】:

4294967295 是 -1,表示为无符号 int32。在这种情况下,它代表indexPath.row-1 == -1 或indexPath.row == 0。

我不确定您为什么要从您的 indexPath.row 中减去 1,但您应该添加一些安全措施来检查边界,以确保您的数组查找不会获取超出边界的元素。

if (indexPath.row == 0) // do something special

或

[self.indexArray objectAtIndex:indexPath.row]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 2018-09-08
    • 2020-03-13
    • 2019-09-11
    相关资源
    最近更新 更多