ios 保存本地数据的方法。

1。
NSString *path = [[NSBundle mainBundle] pathForResource:@"文件名" ofType:@"plist"];
// 文件数据类型是array
NSArray *array=[NSArray arrayWithContentsOfFile:path];
//文件数据类型是*dictionary
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:path];

//1. 创建一个plist文件
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);  www.2cto.com
    NSString *path=[paths    objectAtIndex:0];
    NSLog(@"path = %@",path);
    NSString *filename=[path stringByAppendingPathComponent:@"test.plist"];    
    NSFileManager* fm = [NSFileManager defaultManager];
    [fm createFileAtPath:filename contents:nil attributes:nil];        
    //NSDictionary* dic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    
    //创建一个dic,写到plist文件里
    NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:@"sina",@"1",@"163",@"2",nil];
    [dic writeToFile:filename atomically:YES];
    
    //读文件
    NSDictionary* dic2 = [NSDictionary dictionaryWithContentsOfFile:filename];
    NSLog(@"dic is:%@",dic2);


2。NSUserDefaults的使用


创建一个user defaults方法有多个,最简单得快速创建方法:
   NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];

添加数据到 user defaults:
   [accountDefaults setObject:nameField.text forKey:UserDefaultNameKey];
也可以添加基本数据类型int, float, bool等,有相应得方法

   [accountDefaults setBool:YES forKey:UserDefaultBoolKey];

从user defaults中获取数据:

   [accountDefaults objectForKey:NCUserDefaultNameKey]

  
 [accountDefaults boolForKey: UserDefaultBoolKey];

要点: NSUserDefaults非常好用,并不需要用户在程序中设置NSUserDefaults的全局变量,需要在哪里使用NSUserDefaults的数据,那么就在哪里创建一个NSUserDefaults对象,然后进行读或者写操作。
     针对同一个关键字对应的对象或者数据,可以对它进行重写,重写之后关键字就对应新的对象或者数据,旧的对象或者数据会被自动清理。

3 关于NSUserDefaults保存不了数据的问题

If you terminate your app by pressing the home button (in the Simulator or on the device), your User Defaults will get saved.

如果你按HOME键终止你的应用(真机或者模拟器上),你的值是会被保存的。

If you terminate your app by pressing "Stop" in Xcode (in the Simulator or on the device), your User Defaults might get saved, but there's a good chance they won't. NSUserDefaults persists any changes periodically, and if you terminate the process before they've been persisted, they'll be gone. You can force the save by calling:

[[NSUserDefaults standardUserDefaults] synchronize];

如果你在XCODE中,终止你的应用(在模拟器或者真机上),你的值或许不会被保存。原因在于
你可以使用以下代码强制保存
[[NSUserDefaults standardUserDefaults] synchronize];


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值