Create a model (user)

In. H. Abide by NSCoding protocol

#import <Foundation/Foundation.h>

@interface PDUser : NSObject<NSCoding>

@property(nonatomic,strong)NSString *apiKey;
@property(nonatomic,strong)NSString *apiSecret;
@property(nonatomic,strong)NSString *regDev;

@property(nonatomic,assign)NSInteger user_id;

@end
Copy the code

In. M. Override method encodeWithCoder, initWithCoder


#import "PDUser.h"

@implementation PDUser

-(void)encodeWithCoder:(NSCoder *)aCoder{
     
    [aCoder encodeObject:self.apiKey forKey:@"apiKey"];
    [aCoder encodeObject:self.apiSecret forKey:@"apiSecret"];
    [aCoder encodeObject:self.regDev forKey:@"UUID"];
    [aCoder encodeObject:[NSString stringWithFormat:@"%ld",self.user_id] forKey:@"userid"];

}

-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    
    if(self = [super init]){
        
        self.apiKey = [aDecoder decodeObjectForKey:@"apiKey"];
        self.apiSecret = [aDecoder decodeObjectForKey:@"apiSecret"];
        self.regDev = [aDecoder decodeObjectForKey:@"UUID"];
        self.user_id = [[aDecoder decodeObjectForKey:@"userid"] integerValue];
    
    }
    return self;
}
Copy the code
External use

Save it in NSUserDefaults and get the user out of it.

  • save
PDUser *user = [[PDUser alloc] init]; user.apiSecret = _reBackData.apiSecret; user.apiKey = _reBackData.apiKey; user.regDev = _reBackData.regDev; user.user_id = _reBackData.user_id; NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user]; [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"USERKEY"]; / / saveCopy the code
  • Take out the
NSUserDefaults *userD = [NSUserDefaults standardUserDefaults]; NSData *data = [userD objectForKey:@"USERKEY"]; PDUser *user = [NSKeyedUnarchiver unarchiveObjectWithData:data];Copy the code
Clear data
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
Copy the code