我的应用程序包含几个视图,我想在应用程序启动时显示一个小设置,但用户尚未完成向导。 我知道我可以使用NSUserDefaults实现这一点,但我不确定如何根据NSUserDefaults存储的输入字符串显示特定视图。
我的AppDelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSString *controllerName = [[NSUserDefaults standardUserDefaults] objectForKey:@"WIZARD_VIEW"];
if ([controllerName length]) {
Class controllerClass = NSClassFromString(controllerName);
UIViewController *controller = [[controllerClass alloc] init];
// Override point for customization after application launch.
return YES;
}
然后在viewcontroller文件中,我添加了以下代码作为来自jfaller的建议:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSUserDefaults* standard=[NSUserDefaults standardUserDefaults];
[standard registerDefaults: @{ @"WIZARD_VIEW" : [[self class]description]} ]; [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
NSUserDefaults* standard=[NSUserDefaults standardUserDefaults];
[standard registerDefaults: @{ @"WIZARD_VIEW" : [[self class]description]} ];
[[NSUserDefaults standardUserDefaults] synchronize];
}
但是我该怎么做才能显示在设置中选择的特定视图?
答案 0 :(得分:3)
就个人而言,我会做以下事情:
每次用户转到向导中的新视图时,都会在用户默认值中记录UIViewController:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSUserDefaults standardUserDefaults] setObject:[[self class] description] forKey:WIZARD_VIEW];
[[NSUserDefault standardUserDefaults] synchronize];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:WIZARD_VIEW];
[[NSUserDefault standardUserDefaults] synchronize];
}
当用户重新启动应用程序时(假设在向导中间),重新加载视图:
- (BOOL)application:(UIApplication *)application
willFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// etc.
NSString *controllerName = [[NSUserDefaults standardUserDefaults] objectForKey:WIZARD_VIEW];
if ([controllerName length]) {
Class controllerClass = NSClassFromString(controllerName);
NSViewController *controller = [[controllerClass alloc] init];
// push the controller, or whatever....
}
// etc.
}
答案 1 :(得分:1)
在视图加载时将您所查看的视图写入NSUserDefaults。然后检查didFinishLaunchingWithOptions
中的值。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"current_setup"] isEqualToString:@"1"]) {
//on view 1!
}
}