代码之家  ›  专栏  ›  技术社区  ›  Moshe

从启动到启动存储nsstring(或其他数据)的快速而肮脏的方法?

  •  1
  • Moshe  · 技术社区  · 14 年前

    我希望允许我的用户存储自定义短语,以便在可编辑的UITableView中显示。

    存储这些字符串的快速和肮脏是什么?

    我对iPhone的开发还比较陌生。我知道核心数据,但不知道如何使用它。如果可能的话,我会尽量避开这个特殊的项目。plist文件在这里有可能吗?

    感谢样品代码。

    3 回复  |  直到 9 年前
        1
  •  3
  •   Community CDub    7 年前

    使用 NSUserDefaults . 里面有一些密码 this question .

        2
  •  2
  •   thelaws    14 年前

    如果你想用夹钳,我想这是最快的方法。使用nscoding还有其他方法可以将数据编码到文件中,但您可能需要自定义数据模型类,这更适合保存不适合指定数据模型的更随机的内容。此外,正如已经指出的,nsuserdefaults也是一个选项

    要保存您的工作:

    -(void)applicationWillTerminate:(NSNotification *)notification {
       NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
       NSString *documentsDirectory = [paths objectAtIndex:0];
       NSString *filePath = [documentsDirectory stringByAppendingString:@"info.plist"];
       NSMutableArray *array = [[NSMutableArray alloc] init];
    // Add the objects you want to save to the array here ex: [array addObject:]
       [array writeToFile:filePath atomically:YES];
       [array release];  }
    

    要恢复保存的文件:

    - (void)viewDidLoad {
       NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
       NSString *documentsDirectory = [paths objectAtIndex:0];
       NSString *filePath = [documentsDirectory stringByAppendingString:@"info.plist"];
       if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
           NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
        // Set your vaiables here in the order that you saved them ex. var = [array objectAtIndex:]
           [array release];
       }
       UIApplication *app = [UIApplication sharedApplication];
       [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(applicationWillTerminate:) 
                                                 name:UIApplicationWillTerminateNotification 
                                               object:app];
    
        [super viewDidLoad];}
    

    基本上,当您的应用程序即将退出时,您将创建并排列要保存的对象,并将其写入文件;当您的应用程序再次启动时,您将该文件重新读取到一个数组中,并根据保存的顺序分配变量。然后设置它,这样当应用程序发送其uiapplicationwillterminatenotification时,它会执行代码以将(大概)修改过的变量保存回文件中。

        3
  •  1
  •   David Gelhar    14 年前

    你可能想要 NSDefaults 检查一下 User Defaults Programming Topics 指南。