iOS开发笔记--iOS开发 使用NSUserDefaults 保存数据

来源:互联网 发布:手机翻拍照片软件 编辑:程序博客网 时间:2024/05/22 00:22

NSUserDefaults类似android中的SharedPreferences,可以把数据持久化到设备中。

////  ViewController.h//  // #import <UIKit/UIKit.h> @interface ViewController : UIViewController@property (strong, nonatomic) IBOutlet UILabel *label;@property (strong,nonatomic) NSUserDefaults *userDefaults;- (IBAction)read:(id)sender;- (IBAction)write:(id)sender; @end

////  ViewController.m// // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad{    [super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.    _userDefaults=[NSUserDefaults standardUserDefaults];} - (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.    _userDefaults=nil;}/* 读 */- (IBAction)read:(id)sender {     NSString *string=[_userDefaults valueForKey:@"string"];    _label.text=string;  }/* 写 */- (IBAction)write:(id)sender {    [_userDefaults setObject:@"保存" forKey:@"string"];    [_userDefaults synchronize];}@end

用NSUserDefaults存储的数据下次程序运行的时候依然存在,它把数据存储在什么地方了?如何能够清除?

其实它存储在应用程序内置的一个plist文件里,这个可以根据路径看到。
比如说这个是你的程序沙盒位置
/UsersLibrary/Application Support/iPhoneSimulator/4.1/Applicati*****/29788E40-AF47-45A0-8E92-3AC0F501B7F4/,(这个是应用程序对应在mac上的位置)
这个下面有/Library/Prefereces,里面有个plist文件,存储的就是你的userDefaults
想要删掉的话,用removeObjectForKey或者删掉沙盒,也就是你的应用程序然后重新安装。

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记

原创粉丝点击