0

我从 AppDelegate 获取图像,然后将其设置为 ViewController 的 table.imageView 属性。它向我抛出了一个 NSRangeException:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray     objectAtIndex:]: index (2) beyond bounds (2)'

我确保我的数组和行按 [数组计数] 计数。很困惑。这是代码:

#pragma mark - viewWillAppear
- (void)viewWillAppear:(BOOL)animated {

PBAppDelegate *dataObject = (PBAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *titleRead = dataObject.title;
NSString *descRead = dataObject.desc;
UIImage *imageRead = dataObject.image;


if ([titleRead isEqualToString:@"" ] || [descRead isEqualToString:@""]) {
    // it's nil
} else {
    if (titleRead) {
        [data addObject:[NSArray arrayWithObjects:titleRead, descRead, imageRead, nil]];
        dataObject.title = @"";
        dataObject.desc = @"";
        [tableView reloadData];
    }

    NSUserDefaults *dataDefaults = [NSUserDefaults standardUserDefaults];
    [dataDefaults setObject:[NSArray arrayWithArray:data] forKey:@"dataArrayKey"];
    [dataDefaults synchronize];
}

}

#pragma mark - viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
data = [[NSMutableArray alloc] init];

self.data = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataArrayKey"];
[tableView reloadData];
}

#pragma mark - Table Datasource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath     *)indexPath {

static NSString *cellIdentifier = @"MyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (!cell) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}

cell.textLabel.text = [[data objectAtIndex:indexPath.row] objectAtIndex:0];
cell.detailTextLabel.text = [[data objectAtIndex:indexPath.row] objectAtIndex:1];
cell.imageView.image = [UIImage imageNamed:[[data objectAtIndex:indexPath.row] objectAtIndex:2]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

return cell;
}
4

2 回答 2

1

大概就是这一行:

cell.imageView.image = [UIImage imageNamed:[[data objectAtIndex:indexPath.row] objectAtIndex:2]];

控制台输出显示数组中有 2 个元素。元素从 0 开始;因此您可以访问 objectAtIndex:0 和 objectAtIndex:1。两个将是数组的第三个元素,并且超出范围。

对不起,如果这一切都很明显,只是快速刺伤......享受。:)

编辑imageRead实际上,当您将它添加到数组时 ,问题可能是 nil 。这将导致数组中只有 2 个元素。如果您没有图像,您可以检查,和/或使用 [NSNull null] ...

于 2013-01-19T16:26:04.610 回答
0

通过执行以下操作确保数组实际上有 3 个元素:

NSArray *array = [data objectAtIndex:indexPath.row];
if ([array count] > 2)
{
 cell.imageView.image = [UIImage imageNamed:[array objectAtIndex:2]];
}
于 2013-01-19T19:44:33.570 回答