Getting the selectedIndex of the currently selected tab from a viewcontroller

mensch picture mensch · Oct 27, 2009 · Viewed 7.5k times · Source

I currently have an iPhone application with a tabbar and multiple viewcontrollers. All the views are designed in Interface Builder. I'd like to be able to get the currently selected index of the tabbar from the viewcontroller, but for some reason this property returns (null).

I called the following in the viewDidLoad function of my viewcontroller:

self.tabBarController.selectedIndex

What would be the correct way to do this?

Updated with the code of the AppDelegate class.

MyAppDelegate.h

#import <UIKit/UIKit.h>

@interface MyAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> {
  UIWindow *window;
  UITabBarController *tabBarController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;

@end

MyAppDelegate.m:

#import "MyAppDelegate.h"

@implementation MyAppDelegate

@synthesize window, tabBarController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
  [window addSubview:tabBarController.view];
}

- (void)dealloc {
    [tabBarController release];
    [window release];
    [super dealloc];
}

@end

Answer

Morion picture Morion · Oct 27, 2009

You should have a pointer to your tabbar in your appDelegate class. Your view has no tabbar, so you recieve nil from [self.tabBarController selectedIndex].