iphone - 从上次打开的 UIViewController 打开应用程序

标签 iphone ios objective-c cocoa-touch uiviewcontroller

我需要我的应用记住哪个是最后打开的 UIViewController 所以当应用加载内存不足时,我替换 AppDelegate 中的 rootViewController 属性 其中一个保存在 NSUserDefaults 中:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window = window;

    frontViewController = [[SGLoginScreenViewController alloc] init];

    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:frontViewController];

    self.window.rootViewController = navController;
    [self.window makeKeyAndVisible];
    return YES;
}

我想做的是在每个 ViewControllerViewDidLoad 方法中放入一些代码,并在 NSUserDefaults 中记住它的名字以备后用它在 didFinishLaunchingWithOptions 中,像这样:

[[NSUserDefaults standardUserDefaults] setObject:self forKey:@"currentViewController"];
[[NSUserDefaults standardUserDefaults] synchronize]; 

但是,问题是 XCode 给我这个警告:

*** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '<SGMainScreenFirstTimeViewController: 0x8e1fea0>' of class 'SGMainScreenFirstTimeViewController'.  Note that dictionaries and arrays in property lists must also contain only property values.

关于如何正确实现这整件事有什么想法吗?提前致谢

最佳答案

您只能将符合键值编码(NSString、NSnumber 等)的对象保存在用户默认值中。将类转换为字符串并重新创建知道类名的类将是实现您希望实现的目标的方法。 这将是保存 NSUserDefaults 的好方法

[[NSUserDefaults standardUserDefaults] setObject:NSStringFromClass([self class]); forKey:@"currentViewController"];
[[NSUserDefaults standardUserDefaults] synchronize]; 

为了加载回来,您根据保存的字符串重新创建类,如下所示:

NSString *savedClassName = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentViewController"];
UIViewController *controller = [(UIViewController *)NSClassFromString(savedClassName) alloc] init];

关于iphone - 从上次打开的 UIViewController 打开应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14518599/

相关文章:

iphone - 来自底部的 OpenFeint 通知

iphone - 即时更改 iOS 应用程序的语言

ios - 如何在 TextView / WebView 中进行左对齐和对齐

iphone - 裁剪录制的视频- objective-c

ios - NSURLConnection sendSynchronousRequest 似乎挂起

ios - UITabBarItem 未使用的表达式结果

iphone - 将图像保存到文档目录

iphone - UITextField 光标向后移动

ios - 如果配置文件设置为 "automatic"是否需要更新?

带有 UIView 的 iOS UITableView 自定义页脚