Objective c 如何使上次访问的Viewcontroller成为RootViewController?

Objective c 如何使上次访问的Viewcontroller成为RootViewController?,objective-c,uiviewcontroller,nsuserdefaults,uistoryboard,appdelegate,Objective C,Uiviewcontroller,Nsuserdefaults,Uistoryboard,Appdelegate,我想出来了。谢谢你提供的信息!: UIViewController* vc = (UIViewController*)[[UIStoryboard storyboardWithName:@"iPhone4" bundle:nil] instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"]; if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"cu

我想出来了。谢谢你提供的信息!:

UIViewController* vc = (UIViewController*)[[UIStoryboard storyboardWithName:@"iPhone4" bundle:nil] instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"];

if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"currentViewController"] isEqualToString:@"iPhone4Level1"])
{
    [self.window setRootViewController: vc];
}

不能通过
NSClassFromString
初始化类。它不返回类的实例,而是返回一个类对象。这是一个有助于识别类的Objective C特性。这就是为什么会出现此错误,因为尝试设置为根视图控制器的变量不是视图控制器,因此无法响应视图控制器方法。类使用它们自己的初始值设定项进行初始化

e、 g

或者,如果您正在使用NIB/故事板,请使用其他初始值设定项:

MyViewController* vc = [[MyViewController alloc] initWithNibName: @"myNib" bundle: nil];

要完成您试图完成的任务,您需要一些逻辑来根据保存的类确定要加载的类

e、 g


但是,您最好将一些值定义为标识符(整数、字符串,任何您想要的)并保存这些值,而不是保存类名,因为类可以子类化、重用等。您可能也不希望应用程序中的每个视图控制器类都成为允许的起点。然后,您可以避免这种
NSClassFromString
业务,只需执行一个简单的switch语句或逻辑表达式。

提供有关崩溃的更多详细信息。它发生在哪里,它说了什么,等等。但是我的代码正确吗@shim@shim查看我对NSLogIt的编辑您更新了您的问题,这很好,但您确实不应该删除您的问题,以防将来的访问者想知道您在问什么,以及您尝试了什么,但没有用。在我的项目中,我将'MyViewController*vc=[[MyViewController alloc]initWithNibName:@“myNib”放在哪里捆绑:无];'我会把这个代码放在AppDelegate中吗。我真的很困惑。相同的位置,只是代替了UIViewController*controller=(UIViewController*)NSClassFromString(savedClassName);请看我的编辑。我在app delegate中尝试了你的代码,但它仍然打开到第一个视图。我做错了什么?您是否在视图控制器上设置了带有该标识符的情节提要?
MyViewController* vc = [[MyViewController alloc] initWithNibName: @"myNib" bundle: nil];
MyViewController* vc = (MyViewController*)[[UIStoryboard storyboardWithName:@"MyStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"];
Class c = NSSClassFromString(@"MyClass"
if ([MyViewController class] == c) {
   //load MyViewController, e.g. using init or instantiate from storyboard etc
}
else if ([MyOtherViewController class] == c){
   //load MyOtherViewController
}
//etc