pitachip pitachip - 2 months ago 16
iOS Question

Why does setting tab bar controller's selectedViewController >= 4 throw error when there are more than 5 view controllers?

I have a UITabBarController that I navigate programmatically. Calling the following method:

// UITabBarController subclass

- (void)tabForward
{
NSUInteger selectedIndex = [self.viewControllers indexOfObject:self.selectedViewController];
selectedIndex = selectedIndex + 1;
if ( selectedIndex < [self.viewControllers count] )
self.selectedViewController = [self.viewControllers objectAtIndex:selectedIndex];
}


seems to work fine initially, but then this same line (
self.selectedViewController = [self.viewControllers objectAtIndex:selectedIndex];
) throws the error,
[__NSArrayM insertObject:atIndex:]: object cannot be nil
, when there are more than 5 view controllers and selectedIndex == 4. However, if I just remove any of the view controllers from the tab bar controller to bring the total count to 5 view controllers or below, no error is thrown. This is driving me nuts. Does anyone have any idea what I'm doing wrong?

Answer
// UITabBarController subclass

- (void)tabForward
{
    NSInteger selectedIndex = [self.viewControllers indexOfObject:self.selectedViewController];
    NSInteger nextIndex = selectedIndex + 1;
    if (nextIndex < self.viewControllers.count) {
        if (nextIndex > 3) { // use navigation controller when selectedIndex >= 4
            self.selectedViewController = self.moreNavigationController;
            [self.moreNavigationController pushViewController:self.viewControllers[nextIndex] animated:YES];
        } else {
            self.selectedViewController = self.viewControllers[nextIndex];
        }
    }
}
Comments