3

如果 @"Comments" 数组为 0 而其他两个为 1 或更大,我将收到以下错误。

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'

这是填充self.items数组。

我如何解释某些self.notification(在这种情况下为注释)数组可能为 null 并且仍然可以运行我的代码而不会引发此类错误的事实?

NSDictionary *commentsDict = [NSDictionary dictionaryWithObject:self.notification.Comments forKey:@"Comments"];
NSDictionary *likesDict = [NSDictionary dictionaryWithObject:self.notification.Likes forKey:@"Likes"];
NSDictionary *friendsDict = [NSDictionary dictionaryWithObject:self.notification.Likes forKey:@"Friends"];

self.items = [NSMutableArray array];

[self.items addObject:commentsDict];
[self.items addObject:likesDict];
[self.items addObject:friendsDict];

这是失败的代码:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *dictionary = [self.items objectAtIndex:section];
    NSArray *array = nil;

    if (section == 0) {
        array = [dictionary objectForKey:@"Comments"]; // 0 count
    } else if (section == 1) {
        array = [dictionary objectForKey:@"Likes"]; // 1 count or greater
    } else {
        array = [dictionary objectForKey:@"Friends"]; // 1 count or greater
    }

    return [array count];
}
4

5 回答 5

2

在你的代码前面放一个NSLog(@"Array: %@", self.items);,你会看到数组确实是空的。

于 2011-03-02T09:19:21.050 回答
1

要解决这个问题,您需要查看您的设置self.items方式和实施方式- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

要么self.items提前释放数组,要么你如何返回节数独立于self.items.

于 2011-03-02T20:48:22.563 回答
1

您试图通过不存在的索引获取对象。也许self.items数组没有每个部分索引的对象。从错误消息看来,它self.items实际上是空的(零个对象)。

于 2011-03-02T09:17:56.530 回答
1

也许你定义了太多的部分(超过 self.items 中的项目数):

那么这将失败:

[self.items objectAtIndex:section]
于 2011-03-02T09:19:04.700 回答
0

这是我的一个问题,- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;因为我在更改节标题时只引用了 Comments 数组而不是其他两个数组。

于 2011-03-06T07:34:43.893 回答