NSUserDefaults的使用

[[NSUserDefaults standardUserDefaults] setObject:Year.titleLabel.text forKey:@"Year"];

[Year setTitle:[[NSUserDefaults standardUserDefaults] objectForKey:@"Year"] forState:UIControlStateNormal];



如果存储的数据是自定义类的对象,那么需要归档和反归档


1.首先在自定义的类中实现<NSCoding>协议中的- (id) initWithCoder: (NSCoder *)coder方法和- (void) encodeWithCoder: (NSCoder *)coder方法

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    
    self = [aDecoder decodeObjectForKey:@"userInfoData"];

    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self forKey:@"userInfoData"];

}

 



2.存

NSDictionary *dicUserInfoData = (NSDictionary *)userInfoModel.data;
NSData *dataUserInfoData = [NSKeyedArchiver archivedDataWithRootObject:dicUserInfoData];
[[NSUserDefaults standardUserDefaults] setObject:dataUserInfoData forKey:@"userInfoModel_data"];


3.取

NSData *dataUserInfoData0 = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfoModel_data"];
NSDictionary *dicUserInfoData0 = (NSDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:dataUserInfoData0];
    
UserInfoUserInfoModel *userInfoModel0 = [[UserInfoUserInfoModel alloc] init];
userInfoModel0.data = (UserInfoData *)dicUserInfoData0;
    
UserInfoData *data = userInfoModel0.data;
    
[userInfoModel0 release];

return data;


你可能感兴趣的:(NSUserDefaults)