NSUserDefaults做数据存储也是比较常用,适合轻量级的本地数据存储,读取也很方便。
一、支持的数据类型如下图(NSString、NSArray、NSDictionary、NSData、NSInteger、float、double、BOOL、NSURL)
二、使用Demo
//
// ViewController.m
// NSUserDefaults
//
// Created by City--Online on 15/4/21.
// Copyright (c) 2015年 CYW. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
#if 0 //保存数据
NSString *mystring=@"cuiyw";
int myint=12;
float myfloat=12.0;
double mydouble=12.00;
NSDate *mydate=[NSDate date];
NSArray *myarray=[[NSArray alloc]initWithObjects:@"a",@"b",@"c",nil];
NSDictionary *mydic=[[NSDictionary alloc]initWithObjects:@[@"cui",@"yanwei"] forKeys:@[@"1",@"2"]];
BOOL mybool=YES;
NSData *mydata=[mystring dataUsingEncoding:NSUTF8StringEncoding];
NSURL *myUrl=[[NSURL alloc]initWithString:@"http://www.baidu.com"];
NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
// 设置数据
[userDefaults setObject:mystring forKey:@"mystring"];
[userDefaults setInteger:myint forKey:@"myint"];
[userDefaults setDouble:mydouble forKey:@"mydouble"];
[userDefaults setFloat:myfloat forKey:@"myfloat"];
[userDefaults setObject:mydate forKey:@"mydate"];
[userDefaults setObject:myarray forKey:@"myarray"];
[userDefaults setObject:mydic forKey:@"mydic"];
[userDefaults setBool:mybool forKey:@"mybool"];
[userDefaults setObject:mydata forKey:@"mydata"];
[userDefaults setURL:myUrl forKey:@"myUrl"];
//数据立即保存
[userDefaults synchronize];
NSLog(@"%@",NSTemporaryDirectory());
#endif
#if 1
NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
NSString *myString=[userDefaults stringForKey:@"mystring"];
NSInteger myint=[userDefaults integerForKey:@"myint"];
float myfloat=[userDefaults floatForKey:@"myfloat"];
NSDate *mydate=[userDefaults objectForKey:@"mydate"];
NSArray *myarray=[userDefaults arrayForKey:@"myarray"];
NSDictionary *mydic=[userDefaults dictionaryForKey:@"mydic"];
BOOL mybool=[userDefaults boolForKey:@"mybool"];
NSString *mydata=[[NSString alloc]initWithData:[userDefaults dataForKey:@"mydata"] encoding:NSUTF8StringEncoding] ;
NSURL *myUrl=[userDefaults URLForKey:@"myUrl"];
NSLog(@"myString:%@\nmyint:%ld\nmyfloat:%lf\nmydate:%@\nmyarray:%@\nmydic:%@\nmybool:%d\nmydata:%@\nmyUrl:%@",myString,myint,myfloat,mydate,myarray,mydic,mybool,mydata,myUrl);
//可以通过removeObjectForKey移除
//[userDefaults removeObjectForKey:@"mystring"];
#endif
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
三、运行结果
NSUserDefaults保存在Library/Preferences下