Getting the name of a Controller

2019-08-17 06:15发布

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.

3条回答
再贱就再见
2楼-- · 2019-08-17 06:45
 if ([NSStringFromClass([[appDelegate.myTabBarController selectedViewController] class]) isEqualToString:@"TestViewController"])
{
    //do your stuff here
}
查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-17 06:49

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.

查看更多
Deceive 欺骗
4楼-- · 2019-08-17 06:50

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.

查看更多
登录 后发表回答