如果 @"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];
}