我需要我的应用记住哪个是最后打开的 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;
}
我想做的是在每个 ViewController
的 ViewDidLoad
方法中放入一些代码,并在 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/