IPhone - numberOfRowsInSection error with array calculation

I get the following error if the @ Comments array is 0 and the other two are 1 or more.

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

This fills the array self.items.

How can I explain that some of the arrays self.notification(Comments in this case) may be empty and still work with my code without throwing this type of error?

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];

This is the code in which it does not work:

- (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];
}
+3
source share
5 answers

This was a problem with mine - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;, as I only referred to an array of comments instead of the other two when changing the section title.

0
source

put NSLog(@"Array: %@", self.items);in front of your code and you will see that the array is really empty.

+2

, . , self.items . Fromt , self.items ( ).

+1

, (, self.items):

:

[self.items objectAtIndex:section]
+1

, , self.items - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView.

self.items self.items.

+1

Source: https://habr.com/ru/post/1795693/


All Articles