NSUserDefaults 归档,数据持久化

我这里的方法适用于 model 归档,用户登录数据持久化


1,创建一个model ,要遵守协议 NSCoding 

我创建 UserInfo 

UserInfo.h 文件:

#import


@interface UserInfo : NSObject

@property (nonatomic, strong)NSString *userName;

@property (nonatomic, strong)NSString *userToken;


@end


UserInfo.m 文件:

- (void)encodeWithCoder:(NSCoder *)aCoder{

    [aCoder encodeObject:self.userName forKey:@"userName"];

    [aCoder encodeObject:self.userToken forKey:@"userToken"];

}


- (id)initWithCoder:(NSCoder *)aDecoder{

    self = [super init];

    if (self) {

        self.userName = [aDecoder decodeObjectForKey:@"userName"];

        self.userToken = [aDecoder decodeObjectForKey:@"userToken"];

    }

    return self;

}



2,在需要归档的地方 写归档的方法

//归档

- (void)encode{

    BOOL save = YES;

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    [userDefaults setBool:save forKey:@"save"];

    [userDefaults synchronize];

    

    [NSKeyedArchiver archiveRootObject:_userList toFile:_path];

    

}


3,在需要解归档的地方写上解归档的方法:

//解归档

- (void)decode{

    _userList = [[NSKeyedUnarchiver unarchiveObjectWithFile:_path ]mutableCopy];

    NSLog(@"---解归档---%@", _userList);

    for (UserInfo *user in _userList) {

        NSLog(@"jieguidang  %@", user.userToken);

    }

}


4,在用户进入登录页面的时候  需要先解归档,看看用户是不是有登录过

- (void)loadData{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    _path = [[paths firstObject]stringByAppendingPathComponent:@"userInfo.archiver"];

    BOOL save = NO;

    NSLog(@"地址 :%@", _path);

    NSUserDefaults *uerd = [NSUserDefaults standardUserDefaults];

    if ([uerd boolForKey:@"save"]!= YES) {

        _userList = [NSMutableArray array];

        

    }else{

        save = YES;

        [uerd setBool:save forKey:@"save"];

        [uerd synchronize];

        [self decode];

    }

}



5,用户登录成功后,把用户登录成功后的一些必要数据持久化,在用户再次进入 APP 的时候不用再重新登录:

 UserInfo *userInfo = [[UserInfo alloc]init];

            userInfo.userName = _telephoneNumb;

            userInfo.userToken = news[@"data"][@"token"];

            [_userList addObject:userInfo];

            [self encode];



你可能感兴趣的:(iOS)