0

I have created a custom navigation controller which I call CatalogueNavigationController. This CatalogueNavigationController has a property called currentLevel which is of type int.

On one of my view controllers that are presented within this navigation controller, I would like to get the CatalogueNavigationController's currentLevel value. However, when I try to reference it with self.navigationController.currentLevel, I'm faced with an error that suggests that currentLevel isn't a property of UINavigationController - I know, it's part of CatalogueNavigationController.

CatalogueNavigationController

// .h
@interface CatalogueNavigationController : UINavigationController
@property int currentLevel;

// .m
@implementation CatalogueNavigationController
@synthesize currentLevel;

Initialising View Controller

CatalogueBrowser *catalogue = [[CatalogueBrowser alloc] initWithStyle:UITableViewStyleGrouped andQuery:nil];
CatalogueNavigationController *navigation = [[CatalogueNavigationController alloc] initWithRootViewController:catalogue];
navigation.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentModalViewController:navigation animated:YES];

CatalogueBrowser View Controller

NSLog(@"%i",self.navigationController.currentLevel); //ERROR: Property 'currentLevel' not found on object of type 'UINavigationController *'

The currentLevel variable is decremented when a viewController is popped and incremented when a viewController is pushed, to allow me to keep track of 'how deep' into the navigation the user is. So I need to return it's current state.

I could use Notifications to marry a variable on my view controller and on the CatalogueNavigationController, but surely there's a more elegant solution?

How can I reference self.navigationController to return the value of currentLevel, but have it refer to the CatalogueNavigationController and not UINavigationController?

Dan Hanly
  • 7,829
  • 13
  • 73
  • 134

2 Answers2

1

I think the best solution, is to test if the navigationController is of the type you want, here explained: In Objective-C, how do I test the object type?. And if it is true you cast it to your object and then check the value you want.

Info in casting objects: ios custom NSObject casting.

Hope it Helps!

Community
  • 1
  • 1
LFCPirex
  • 79
  • 9
  • Cheers for this, but casting in this way will always retrieve the initialised version, not the current instance. Within my CatalogueNavigationController, I increment/decrement currentLevel, which NSLog outputs correctly, with this method, it always returns 0. – Dan Hanly Jun 22 '12 at 15:40
0

I stumbled upon the same situation. I think the solution is this:

CatalogueNavigationController *navController = (CatalogueNavigationController *)self.navigationcontroller;

NSLog(@"%i", navController.currentLevel);
Tuslareb
  • 1,200
  • 14
  • 21