zoukankan      html  css  js  c++  java
  • <IOS>开发中存储文件及配置的方式

    1.write to方式保存到沙盒目录下的documents文件夹下:

    这种方式适合字符串数组的存储。

    //获得当前程序的沙盒目录路径
    NSString *path = NSHomeDirectory();
    //拼接要保存的文件全路径,这个方法会自动在@“Document...”前面加斜杠
    path = [path stringByAppendingPathComponent:@"Documents/student.plist"];///从文件创建数组
    NSArray *array = [NSArray arrayWithContentsOfFile:path];
    //将内容写入文件中
    [mArray writeToFile:path atomically:YES];

    2.NSUserDefaults的使用:(优点是不用关心存储格式,存取操作很方便,用于存储小的变量)(对同一个关键字赋值将会对数据重写,旧数据被清理)

      创建一个user defaults

        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];  

      添加数据到 user defaults:

            [ud setObject:nameField.text forKey:UserDefaultNameKey];

      也可以添加基本数据类型int, float, bool等,有相应得方法

            [ud setBool:YES forKey:UserDefaultBoolKey];

      从user defaults中获取数据:

          [ud objectForKey:NCUserDefaultNameKey]

        [ud boolForKey: UserDefaultBoolKey];

      在程序进入后台执行或者有需要的时候进行

        [ud synchonize];

    3.[NSBundle mainBundle]方式

      bundle是一个目录,其中包含了程序会使用到的资源. 这些资源包含了如图像,声音,编译好的代码等等。我们的程序是一个bundle. 在Finder中,一个应用程序看上去和其他文件没有什么区别. 但是实际上它是一个包含了nib文件,编译代码,以及其他资源的目录. 我们把这个目录叫做程序的main bundle。bundle可用于本地化。

      NSBundle *myBundle = [NSBundle mainBundle];//得到程序的main bundle

      NSBundle *goodBundle = [NSBundle bundleWithPath:@"~/.myApp/Good.bundle"];//从指定路径来取得bundle

      //访问bundle中的资源

      NSString *path = [goodBundle pathForImageResource:@"Mom"]; 

      NSImage *momPhoto = [[NSImage alloc] initWithContentsOfFile:path];

      //bundle中可以包含一个库. 如果我们从库得到一个class, bundle会连接库,并查找该类:

      Class newClass = [goodBundle classNamed:@"Rover"];
      id newInstance = [[newClass alloc] init];

      如果不知到class名,也可以通过查找主要类来取得
      Class aClass = [goodBundle principalClass];
      id anInstance = [[aClass alloc] init];

    4.数据库

  • 相关阅读:
    static、final、this、super关键
    细节二:参数、引用类型、实例化
    枚举类型
    单例模式
    细节一:字符串、switch、默认值、数组
    类属性和类方法
    装饰器模式
    TreeSet
    可见参数和增强for以及自动拆装箱
    静态导入
  • 原文地址:https://www.cnblogs.com/robinkey/p/2770543.html
Copyright © 2011-2022 走看看