因NSRangeException(NSMutableArray)而导致的应用程序终止

时间:2015-08-20 20:58:45

标签: ios objective-c arrays uitableview parse-platform

我试图从Parse检索上传的thumbnailPhotos以在UITableViewCells中显示它们,但我每次都会抛出异常。错误代码如下:"由于未捕获的异常终止应用程序' NSRangeException',原因:' *** - [__ NSArrayM objectAtIndex:]:索引1超出边界[0 .. 0]'"
这是我的代码:

- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];

PFQuery *query = [PFQuery queryWithClassName:@"Events"];
[query orderByDescending:@"date"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (error) {
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    } else {
        self.events = (NSMutableArray *) objects;
        [self.tableView reloadData];

        for (PFObject *event in self.events) {

            NSInteger index = [self.events indexOfObject:event];

            PFFile *imageFile = [event objectForKey:@"thumbnailImage"];

            [imageFile getDataInBackgroundWithBlock:^(NSData *result, NSError *error) {

                if (error) {
                    //Handle Error
                } else {

                    UIImage *image = [UIImage imageWithData:result];

                    if (self.thumbnailPhotos == nil) {

                        self.thumbnailPhotos = [NSMutableArray array];
                        self.thumbnailPhotos[index] = image;
                    } else {

                    self.thumbnailPhotos[index] = image;
                    }

                    [self.tableView reloadData];
                }

            }];
        }
    }
}];

}

的cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *reuseIdentifier = @"Cell";
EventsTableViewCell *cell = (EventsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];

PFObject *event = [self.events objectAtIndex:indexPath.row];

NSDate *date = [event objectForKey:@"date"];

NSString *dateString = [self.dateFormat stringFromDate:date];
NSString *timeString = [self.timeFormat stringFromDate:date];
NSLog(@"IndexPath.row = %ld", (long)indexPath.row);

if ([self.thumbnailPhotos objectAtIndex:indexPath.row] != nil) {

    cell.imageView.image = self.thumbnailPhotos[indexPath.row];
} else {
    NSLog(@"Nil, Application will crash!");
}

cell.eventNameLabel.text = [event objectForKey:@"title"];
cell.dateLabel.text = dateString;
cell.timeLabel.text = timeString;
[cell.timeLabel sizeToFit];

return cell;

}`

我不得不添加self.events的索引值,因为thumbnailPhotos以不同的速度下载,所以我的Cell总是为错误的事件显示错误的照片。 我希望这足以解决问题。

1 个答案:

答案 0 :(得分:1)

应用程序崩溃是因为thumbnailPhotos在索引处没有任何对象用于赋值。请使用以下代码。

更新了代码,支持词典保存缩略图

 /*

     Define events as NSMutableArray which holds all events 
     Define thumbnailPhotos as NSMutableDictionary which holds thumbnail image for index as key

     */

        //Create a weak Reference of self for accessing self within block

        __weak __typeof(self)weakSelf = self;
        PFQuery *query = [PFQuery queryWithClassName:@"Events"];
        [query orderByDescending:@"date"];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (error) {
                NSLog(@"Error: %@ %@", error, [error userInfo]);
            } else {
                //Create a strong reference for updating the UI
                __strong __typeof(weakSelf)strongSelf = weakSelf;

                //Assign the events to instance object
                strongSelf.events = [NSMutableArray arrayWithArray:objects];

                //Alloced thumbnail dictionary
                strongSelf.thumbnailPhotos = [NSMutableDictionary dictionary];

                //Reload tableView so that data will be visible
                [strongSelf.tableView reloadData];

                for (PFObject *event in strongSelf.events) {

                    //Define index as block type because we have to use this instance within block
                   __block NSInteger index = [strongSelf.events indexOfObject:event];

                    PFFile *imageFile = [event objectForKey:@"thumbnailImage"];
                    [imageFile getDataInBackgroundWithBlock:^(NSData *result, NSError *error) {

                        if (error) {
                            //Handle Error
                        } else {

                            UIImage *image = [UIImage imageWithData:result];

                            //Set the image against index
                            [strongSelf.thumbnailPhotos setObject:@"" forKey:@(index)];

                            //Reload only cell for which image is just downloaded
                            [strongSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
                        }

                    }];
                }
            }
        }];

<强>更新 修改你的cellForRowAtIndexPath,如下所示

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuseIdentifier = @"Cell";
    EventsTableViewCell *cell = (EventsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];

    PFObject *event = [self.events objectAtIndex:indexPath.row];

    NSDate *date = [event objectForKey:@"date"];

    NSString *dateString = [self.dateFormat stringFromDate:date];
    NSString *timeString = [self.timeFormat stringFromDate:date];
    NSLog(@"IndexPath.row = %ld", (long)indexPath.row);

    if ([self.thumbnailPhotos valueForKey:@(indexPath.row)]) {

        cell.imageView.image = [self.thumbnailPhotos valueForKey:@(indexPath.row)];
    } else {
        NSLog(@"Nil, Application will crash!");
    }

    cell.eventNameLabel.text = [event objectForKey:@"title"];
    cell.dateLabel.text = dateString;
    cell.timeLabel.text = timeString;
    [cell.timeLabel sizeToFit];

    return cell;
}

在此实现缩略图中,图像将保存到字典中,而第二次重载tableView是基于单元格而不是重新加载完整的tableView以进行单个缩略图下载。