-2

我有一些使用表格视图的经验。这一次,我尝试从数组中加载它(从技术上讲,从字典中加载,但是 allKeys 参数是一个 NSArray),但是,我只是得到了这个异常

-[__NSArrayI objectAtIndex:]: index 10 beyond bounds [0 .. 9]

现在,我的数组有 11 个键长,这意味着它将计为 10(因为 Obj-C 也计为 0)。这里说它的计数是 9。我尝试了几种不同的方法:

  • 将字典的初始化移动到- (void)awakeFromNib
  • NSArray使用所有键创建一个单独的
  • 刚上市11

但他们都给我例外!

更新

我注意到你们中的一些人说我的数组只有 10 个对象长,但是如果我将它设置为10,我会丢失一个对象:

如您所见,有 11 个键

断点告诉 11...

在此处输入图像描述

使用 10 个项目时没有“加速 X”项目,明白吗?

在此处输入图像描述

NSLog以与返回行数相同的方法说不同于 10

4

1 回答 1

1

The fact of the matter is that your array is 10 items long. The comments above aren't saying "you should remove "Acceleration X" to make it 10 items long", they're saying "you're mistaken in your belief that your array is 11 items long".

Without seeing more code, it's difficult to say what's really going on here; but anyway, you shouldn't be using -allValues, because the ordering in that array is undefined, which makes it unsuitable for use backing a table view.

Instead, you should keep an array of the keys of the dictionary in whatever order you want them to display, and then reference _items[key] directly.

For example:

_keys = 
@[
    @"Red",
    @"Orange",
    @"Yellow",
    @"Green",
    @"Blue",
    @"Indigo",
    @"Violet"
];

_dictionary = 
@{
    @"Blue": @"Battle",
    @"Green": @"Gave",
    @"Indigo": @"In",
    @"Orange": @"Of",
    @"Red": @"Richard",
    @"Violet": @"Vain"
    @"Yellow": @"York",
};

- (NSString *)labelTextForIndexPath:(NSIndexPath *)indexPath
{
    return _keys[indexPath.row];
}

- (NSString *)detailLabelTextForIndexPath:(NSIndexPath *)indexPath
{
    return _dictionary[_keys[indexPath.row]];
}
于 2013-10-14T08:05:37.913 回答