views:

52

answers:

3

Hello!

I have an iPhone application with a TabBarController. I can access the current ViewController with

[appDelegate.myTabBarController selectedViewController]

But how can I get the name of this controller?

For example the name of the selected ViewController is "TestViewController". How can I get this string/name? I want to check if the current ViewController is "TestViewController".

Thanks a lot in advance & Best Regards.

+2  A: 

You can do this in this manner:

if([[appDelegate.myTabBarController selectedViewController] isKindOfClass:[TestViewController class]])
{
NSLog(@"Yes I am the controller you want.");
}

Hope this helps.

Madhup
A: 

you can make a subclass of UIViewController class and add property, for example

@property(nonatomic, retain) NSString* name;

then make all of your viewControllers subclasses of the class with name property. then just set the name of the controller in your -(id)init or -(void)viewDidLoad method to be able to get access to it when you need.

the other way is to make some dictionary of class-name pairs. smth like this

[myDictionary setValue:stringClassName forKey:[MyViewController class]];

make this dictionary available from all over the app - and you will be able to get name for each class at any time you want if this class registered in your dictionary.

Morion
+1  A: 
 if ([NSStringFromClass([[appDelegate.myTabBarController selectedViewController] class]) isEqual:@"TestViewController"])
{
//do your stuff here
}
F.Santoni
You're comparing strings, so you should use `-[NSString isEqualToString:]`. But this is unnecessary. Just use `-[NSObject isKindOfClass:]`.
Jonathan Sterling
Sure, you're right, but I'm just giving the useful function NSStringFromClass() here
F.Santoni