方法很簡單回挽,一行代碼就可以搞定
//保存
- (void)saveValue:(NSString *)value forKey:(NSString *)key
{
[[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
}
//讀取
- (void)readValueforKey:(NSString *)key
{
[[NSUserDefaults standardUserDefaults] objectForKey:key];
}
注意
- NSUserDefault只能保存特定類型的對象:
NSData, NSString, NSNumber, NSDate, NSArray, NSDictionary
没咙。如果想要存儲其它類型,需要將打包成NSData
類型厅各。 - 如果保存其他類型的對象镜撩,會報錯
[User Defaults] Attempt to set a non-property-list object <xxx: 0x170029600> as an NSUserDefaults/CFPreferences value for key str
自定義Model打包NSData
類型
- 新建一個類
Model
,實(shí)現(xiàn)NSCoding協(xié)議
Model.h
Model.m#import <Foundation/Foundation.h> @interface Model : NSObject<NSCoding> @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *number; @property (nonatomic, assign) int user_id; @end
#import "Model.h" @implementation Model - (void)encodeWithCoder:(nonnull NSCoder *)aCoder { [aCoder encodeObject:_name forKey:@"name"]; [aCoder encodeObject:_number forKey:@"number"]; [aCoder encodeObject:[NSNumber numberWithInt:_user_id] forKey:@"user_id"]; } - (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder { self = [super init]; if (self) { _name = [aDecoder decodeObjectForKey:@"name"]; _number = [aDecoder decodeObjectForKey:@"number"]; _user_id = [[aDecoder decodeObjectForKey:@"user_id"] intValue]; } return self; } @end
- 在需要打包成
NSData
的地方//存數(shù)據(jù) NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model]; [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"data"]; //取數(shù)據(jù) NSData *daa = [[NSUserDefaults standardUserDefaults] objectForKey:@"data"]; Model *newModel = [NSKeyedUnarchiver unarchiveObjectWithData:daa];