代码之家  ›  专栏  ›  技术社区  ›  Mc.Lover

带“记住上次用户操作”功能的iPhone应用程序

  •  0
  • Mc.Lover  · 技术社区  · 15 年前

    嗨,我想创建一个应用程序,我的应用程序记住最后一个用户操作,这意味着用户发现自己和上次运行应用程序时在同一个页面上。 如何实现这一点?

    2 回复  |  直到 15 年前
        1
  •  1
  •   Yannick Loriot    15 年前

    您可以使用nsuserdefaults为应用程序存储一些变量,以便在应用程序关闭后检索这些变量。 为例:

    // Set the name of the view
    [[NSUserDefaults standardUserDefaults] setObject:@"viewName" forKey:@"lastViewName"];
    

    要检索用户的最后一个操作:

    // Retrieve the last view name
    NSString *lastViewName = [[NSUserDefaults standardUserDefaults] stringForKey:@"lastViewName"];
    

    但您可以添加字符串以外的内容。


    编辑:

    在头文件上定义类似的常量:

    #define HOME_VIEW 0
    #define VIEW1 1
    #define VIEW2 2
    

    加载视图时,将当前常量视图存储为StandardUserDefaults。例如,视图1:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        // Set the name of the view
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:VIEW1] forKey:@"lastView"];
    
    }
    

    当应用程序加载时,检索常量并加载相应的视图:

    - (void)applicationDidFinishLaunching:(UIApplication *)application {
       // Retrieve the last view name
       NSInteger constantView = [[NSUserDefaults standardUserDefaults] integerForKey:@"lastView"];
    
       switch(constantView) {
          case HOME_VIEW : //load your UIViewController
              break;
          case VIEW1 : // load your VIEW1
              break;
          //...
       }
    }
    

    我还没有测试过这段代码,但它是这样做的。

        2
  •  1
  •   willcodejavaforfood    15 年前

    使用应用程序委托并重写方法:

    - (void)applicationWillTerminate:(UIApplication *)application
    

    在这里,您可以保存最后一次可见的视图以及它所处的状态(如有必要,还可以保存其他视图),并将其持久化。

    然后,当您再次启动应用程序时,您将加载保存的状态,并使用它来确定哪些视图应该可见。

    有几种方法可以在iPhone SDK中保存数据,请阅读 this guide 有关如何执行此操作的详细信息。