下面就来做一个简单的demo:
- (IBAction)click:(id)sender {
[senderresignFirstResponder];
}
#import "DXWViewController.h" @interface DXWViewController () @end @implementation DXWViewController - (void)viewDidLoad { [super viewDidLoad]; //获得NSUserDefaults NSUserDefaults *user = [NSUserDefaults standardUserDefaults]; //对NSUserDefaults进行赋值 // [user setObject:@"小明" forKey:@"name"]; // [user setInteger:20 forKey:@"age"]; // [user synchronize];//从缓存写入文件 //从NSUserDefaults通过key获取值 if ([user objectForKey:@"name"] != nil) { self.txtName.text = [user objectForKey:@"name"]; self.txtAge.text = [NSString stringWithFormat:@"%d",[user integerForKey:@"age"]]; } } - (void)dealloc { [_txtName release]; [_txtAge release]; [super dealloc]; } - (IBAction)click:(id)sender { NSUserDefaults *user = [NSUserDefaults standardUserDefaults]; [user setObject:self.txtName.text forKey:@"name"]; [user setInteger:[self.txtAge.text intValue] forKey:@"age"]; [user synchronize];//从缓存写入文件 }
//获取沙盒文件路径
-(NSString *)getPath
{
//用来获得Document地址
NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//注意:这里是NSDocument不是NSDocumentation,特别注意
NSLog(@"%@",arr);
//在地址上增加文件
NSString *path = [arr[0] stringByAppendingPathComponent:@"abc.plist"];
NSLog(@"%@",path);
return path;
}
//创建自定义文件,并存储或者获取文件中数据- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *arr = @[@"aaa",@"bbb",@"ccc"];
[arr writeToFile:[self getPath] atomically:YES];
//判断是否有文件
if([[NSFileManager defaultManager] fileExistsAtPath:[self getPath]])
{
arr = [NSArray arrayWithContentsOfFile:[self getPath]];
NSLog(@"%@",arr);
}
}
//获取应用
UIApplication *app = [UIApplicationsharedApplication];
//在通知中心添加一个观察者,当符合UIApplicationWillResignActiveNotification条件时,调用方法
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(save:) name:UIApplicationWillResignActiveNotificationobject:app];
-(void)save:(id)sender
{
NSArray *arr = @[self.text1.text1,self.text2.text];
[arr writeToFile:[selfgetPath] atomically:YES];
}