一:先看一个小demo 使用NSUserDefaults实现填写几个信息和获取系统相册库图片同时存储。
#import "ViewController.h"
@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>
//此部分是在Main.storyboard中拖控件并进行连线相关联获取的。
@property (weak, nonatomic) IBOutletUITextField *firstNameTextfield;
@property (weak, nonatomic) IBOutletUITextField *secondNameTextfield;
@property (weak, nonatomic) IBOutletUITextField *ageTextfeild;
@property (weak, nonatomic) IBOutletUIImageView *chooseImageView;
- (IBAction)save:(id)sender;
- (IBAction)ChooseImage:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Get the stored data before the view loads在视图出现之前获取数据显示在界面上。
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *firstName = [defaults objectForKey:@"firstName"];
NSString *lastName = [defaults objectForKey:@"secondName"];
NSInteger age = [defaults integerForKey:@"age"];
NSString *ageString = [NSStringstringWithFormat:@"%ld",(long)age];
NSData *imageData = [defaults dataForKey:@"image"];
UIImage *contactImage = [UIImageimageWithData:imageData];
// Update the UI elements with the saved data
self.firstNameTextfield.text = firstName;
self.secondNameTextfield.text = lastName;
self.ageTextfeild.text = ageString;
self.chooseImageView.image = contactImage;
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)save:(id)sender {
// Hide the keyboard 去除键盘
[self.firstNameTextfieldresignFirstResponder];
[self.secondNameTextfieldresignFirstResponder];
[self.ageTextfeildresignFirstResponder];
// Create strings and integer to store the text info
NSString *firstName = [self.firstNameTextfieldtext];
NSString *secondName = [self.secondNameTextfieldtext];
NSInteger age = [[self.ageTextfeildtext] integerValue];
// Create instances of NSData 把图片转为NSData进行存储
UIImage *contactImage = self.chooseImageView.image;
NSData *imageData = UIImageJPEGRepresentation(contactImage, 100);
// Store the data 保存数据
NSUserDefaults *defaults = [NSUserDefaultsstandardUserDefaults];
[defaultssetObject:firstName forKey:@"firstName"];
[defaultssetObject:secondName forKey:@"secondName"];
[defaultssetInteger:age forKey:@"age"];
[defaultssetObject:imageData forKey:@"image"];
[defaultssynchronize];
UIAlertView *alert=[[UIAlertViewalloc]initWithTitle:@"温馨提示"message:@"数据保存成功!"delegate:selfcancelButtonTitle:nilotherButtonTitles:@"确定",nil];
[alertshow];
NSLog(@"Data saved");
}
- (IBAction)ChooseImage:(id)sender {
UIImagePickerController *picker=[[UIImagePickerControlleralloc]init];
picker.delegate=self;//设置代理
picker.allowsEditing=YES;//允许编辑
picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
[selfpresentViewController:picker animated:YEScompletion:^{}];
}
#pragma mark---Image Picker Delegate--------
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *image=[infoobjectForKey:UIImagePickerControllerOriginalImage];
self.chooseImageView.image = image;
[picker dismissViewControllerAnimated:YEScompletion:^{
}];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YEScompletion:^{
}];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSLog(@"成功!");
}
@end
效果为:
学习NSUserDefaults
1) iOS数据持久化之使用NSUserDefaults存储数据,NSUserDefaults是一个单例,在整个程序中只有一个实例对象.
2) iOS下可以使用NSUserDefaults、sqlite、CoreData几种常用的方式来存储数据,其中NSUserDefaults用来存储类似用户的配置等这些的数据,后两者用户存储大批量和比较复杂的数据。
NSUserDefaults适合存储轻量级的本地数据,比如要保存一个登陆界面的数据,用户名、密码之类的,个人觉得使用NSUserDefaults是首选。下次再登陆的时候就可以直接从NSUserDefaults里面读取上次登陆的信息咯。因为如果使用自己建立的plist文件什么的,还得自己显示创建文件,读取文件,很麻烦,而是用NSUserDefaults则不用管这些东西,就像读字符串一样,直接读取就可以了。
3) NSUserDefault的使用比较简单:
创建NSUserDefaults对象之后即可往里面添加数据,它支持的数据类型有NSString、 NSNumber、NSDate、 NSArray、NSDictionary、BOOL、NSInteger、NSFloat等系统定义的数据类型,如果要存放自定义的对象(如自定义的类对象),则必须将其转换成NSData存储:
往NSUserDefaults添加数据后,它们就变成了全局的变量,App中即可读写NSUserDefault中的数据:
如果想删除某个数据项,可以使用removeObjectForKey删除数据:
需要注意的是,NSUserDefaults是定时把缓存中的数据写入磁盘的,而不是即时写入,为了防止在写完NSUserDefaults后程序退出导致的数据丢失,可以在写入数据后使用synchronize强制立即将数据写入磁盘。
// 注意:对相同的Key赋值约等于一次覆盖,要保证每一个Key的唯一性.值得注意的是:
NSUserDefaults 存储的对象全是不可变的(这一点非常关键,弄错的话程序会出bug),例如,如果我想要存储一个 NSMutableArray对象,我必须先创建一个不可变数组(NSArray)再将它存入NSUserDefaults中去,取出数据是一样的,想要用NSUserDefaults中的数据给可变数组赋值.