问题
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.
回答1:
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.
回答2:
if ([NSStringFromClass([[appDelegate.myTabBarController selectedViewController] class]) isEqualToString:@"TestViewController"])
{
//do your stuff here
}
回答3:
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.
来源:https://stackoverflow.com/questions/1973929/getting-the-name-of-a-controller