不管是Android、H5仍是PC端,都有須要將數據保存到本地,後續獲取使用的需求,例如Key-Value保存,在Android中提供了SharedPreferences來保存,iOS則提供了NSUserDefaults。json
在NSUserDefaults中,能夠保存的數據結構有:數組
若是須要保存自定義對象,則須要將對象歸檔爲NSData,再進行保存。類比安卓的話,安卓要將自定義對象保存到SharedPreferences,有2種方式:bash
iOS的歸檔,應該就相似Java的序列化和反序列化機制。數據結構
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
複製代碼
//注意要保存的對象object在前,key在後
[defaults setObject:object forKey:key];
//例如:保存字符串
[defaults setObject:@"Wally" forKey:@"NAME"];
//保存Number對象
[defaults setObject:number forKey:@"NUMBER"];
複製代碼
//用key獲取保存的對象,返回值爲id類型,因此能夠接任何指針
id object = [defaults objectForKey:key];
//例如:獲取保存的字符串
id name = [defaults objectForKey:@"NAME"];
NSLog(@"名字: %@", name);
//獲取保存的Number對象
id num = [defaults objectForKey:@"NUMBER"];
NSLog(@"num: %@", num);
複製代碼
[defaults synchronize];
複製代碼
//使用key刪除保存的值
[defaults removeObjectForKey:@"ARRAY"];
複製代碼
NSUserDefaults能夠存儲上面說到的6種類型,蘋果爸爸還給咱們提供了直接轉換出對應類型的方法,避免每次都寫強轉代碼。ui
//存儲Int值
[defaults setInteger:123 forKey:@"INT"];
//存儲布爾值
[defaults setBool:YES forKey:@"BOOL"];
//存儲浮點型
[defaults setFloat:3.14 forKey:@"FLOAT"];
//存儲數組
NSArray* arr = [NSArray arrayWithObjects:@"Wally", @"Barry", @"Rose", nil];
[defaults setObject:arr forKey:@"ARRAY"];
複製代碼
//獲取Int值
NSLog(@"int: %ld", [defaults integerForKey:@"INT"]);
//獲取BOOL布爾值
NSLog(@"bool: %d", [defaults boolForKey:@"BOOL"]);
//獲取浮點值
NSLog(@"float: %f", [defaults floatForKey:@"FLOAT"]);
//獲取數組
NSArray* arr = [defaults objectForKey:@"ARRAY"];
NSLog(@"%@", arr);
複製代碼
上面說到若是須要保存自定義對象,須要將對象轉爲NSData再進行保存。例如咱們保存用戶登陸信息,保存用戶名和密碼,操做分爲如下步驟:atom
//文件:FSUser.h
@interface FSUser : NSObject<NSCoding>
/**
* 用戶名
*/
@property(nonatomic, strong) NSString *username;
/**
* 密碼
*/
@property(nonatomic, strong) NSString *password;
/**
* 獲取對象全部屬性組合到的一個字符串
*/
- (NSString *) toString;
@end
複製代碼
//文件:FSUser.m
@implementation FSUser
/**
* 恢復
*/
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
self.username = [coder decodeObjectForKey:@"_username"];
self.password = [coder decodeObjectForKey:@"_password"];
}
return self;
}
/**
* 歸檔寫入
*/
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:_username forKey:@"_username"];
[coder encodeObject:_password forKey:@"_password"];
}
- (NSString *)toString {
return[NSString stringWithFormat:@"用戶名: %@, 密碼: %@", _username, _password];
}
@end
複製代碼
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
//存儲自定義對象
FSUser *user = [[FSUser alloc] init];
user.username = @"Wally";
user.password = @"123456";
//歸檔保存
NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:user];
[defaults setObject:userData forKey:@"USER"];
複製代碼
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
//獲取自定義對象
NSData *userData = [defaults objectForKey:@"USER"];
//解檔,恢復對象
FSUser *user = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
//輸出:用戶名: Wally, 密碼: 123456
NSLog(@"%@", [user toString]);
複製代碼