iPhone - 数组计数的numberOfRowsInSection错误

如果@“Comments”数组为0且其他两个为1或更大,则会出现以下错误。
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'
这填充了
self.items
数组。 我如何解释这样一个事实:某些
self.notification
(在这种情况下为注释)数组可能为空并仍然运行我的代码而不会抛出此类错误?
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];
}
    
已邀请:
在你的代码前放一个
NSLog(@"Array: %@", self.items);
,你会发现数组确实是空的。     
您试图通过不存在的索引来获取对象。也许
self.items
数组没有每个部分索引的对象。从错误消息看起来
self.items
实际上是空的(零对象)。     
也许你定义了太多的部分(超过self.items中的项目数): 然后这会失败:
[self.items objectAtIndex:section]
    
要解决这个问题,你需要看看如何设置
self.items
以及如何实现
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
self.items
要么提前释放数组,要么返回的部分数量与
self.items
无关。     
这是我的
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
的问题,因为在更改节标题时我只引用了Comments数组而不是其他两个。     

要回复问题请先登录注册