我从 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;
}