Resolved Trouble with UITabBarControllerDelegate protocol

Discussion in 'iOS Programming' started by brontosaurus, Mar 1, 2012.

  1. brontosaurus, Mar 1, 2012
    Last edited: Mar 2, 2012

    brontosaurus macrumors newbie

    Mar 1, 2012
    Yakima, WA (no where USA)
    I'm experimenting with the UITabBarControllerDelegate methods for the first time, but my app crashes ("Thread 1: Program received signal: "EXC_BAD_ACCESS") when a tab bar item is tapped.

    Setup: Xcode 4.2.1, ARC, everything in storyboard, for iPhone, and I'm using the tab bar controller template.

    A custom class, MyTabBarControllerDelegateClass, conforms to the UITabBarControllerDelegate protocol in order to handle messages from the tab bar controller.

    I set the tab bar controller's delegate property in the following app delegate method:
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
        UITabBarController *tabBarVC = (UITabBarController *)self.window.rootViewController;
        MyTabBarControllerDelegateClass *delegate = [[MyTabBarControllerDelegateClass alloc] init];
        tabBarVC.delegate = delegate;
        return YES;
    Here's the implementation of my MyTabBarControllerDelegateClass class (yea, bad idea to include the word class in class names):
    @implementation MyTabBarControllerDelegateClass
    - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
        NSLog(@"tab bar item selected");
    There's not much else going on in this app because it's just a practice app. Actually, I have barely touched the source code because I started from the tab bar template and I'm using storyboard. Anyway, when I run the app, it loads okay. Then I tap a tab bar item and BOOM, CRASH, SPLAT!

  2. kayloh20 macrumors regular

    Apr 8, 2010
    Chicago, IL
    This is actually due to ARC (though not its fault)

    The system is releasing MyTabBarControllerDelegateClass at the end of the loop, which is after it's finished displaying the tab bar controller (or maybe before it displays), and because delegates aren't retained by the object, it's trying to send the didSelectViewController method to a non-existent MyTabBarControllerDelegateClass.

    Easiest way to 'fix' this would be to create a strong property or an instance variable of MyTabBarControllerDelegateClass.
  3. brontosaurus thread starter macrumors newbie

    Mar 1, 2012
    Yakima, WA (no where USA)
    nice catch!

    I did your fix and now it works!

    Thanks a million for catching that mistake. I'm having much better luck here in this forum getting my questions answered regarding iOS than I did at stack overflow. Again thanks.

Share This Page