iOS自定义类 - NSKeyedArchiver归档自定义类

1.头文件

#import <Foundation/Foundation.h>

@interface ZRQQLoginSingleton : NSObject<NSCoding>

@property (nonatomic, copy) NSString *accessToken;

@property (nonatomic, copy) NSString *openId;

@property (nonatomic, strong) NSDate *expiredDate;

@property (nonatomic, copy) NSString *avatarSmall;

@property (nonatomic, copy) NSString *avatarStandard;

@property (nonatomic, copy) NSString *nickName;

@end

2.源文件

@implementation ZRQQLoginSingleton

/**
 * 对需要逆归档的属性进行解码
 **/
- (instancetype)initWithCoder:(NSCoder *)decoder
{
    if (self = [super init]) {
    
        self.accessToken = [decoder decodeObjectForKey:@"accessToken"];
        self.openId = [decoder decodeObjectForKey:@"openId"];
        self.expiredDate = [decoder decodeObjectForKey:@"expiredDate"];
        self.avatarSmall = [decoder decodeObjectForKey:@"avatarSmall"];
        self.avatarStandard = [decoder decodeObjectForKey:@"avatarStandard"];
        self.nickName = [decoder decodeObjectForKey:@"nickName"];
    }
    return self;
}

/**
 * 对需要归档的属性编码
 **/
- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:self.accessToken forKey:@"accessToken"];
    [encoder encodeObject:self.openId forKey:@"openId"];
    [encoder encodeObject:self.expiredDate forKey:@"expiredDate"];
    [encoder encodeObject:self.avatarSmall forKey:@"avatarSmall"];
    [encoder encodeObject:self.avatarStandard forKey:@"avatarStandard"];
    [encoder encodeObject:self.nickName forKey:@"nickName"];
}

@end

3.对该类进行归档

/**
 * 归档该类
 */
- (void)writeObjectToFile
{
    [NSKeyedArchiver archiveRootObject:self toFile:QQLoginFilePath];
}

4.逆归档该类

/**
 * 逆归档该类
 */
- (void)getObjectFromFile
{
    if([[NSFileManager defaultManager] fileExistsAtPath:QQLoginFilePath]){
        ZRQQLoginSingleton *qqlogin = [NSKeyedUnarchiver unarchiveObjectWithFile:QQLoginFilePath];
        self.accessToken = qqlogin.accessToken;
        self.openId = qqlogin.openId;
        self.expiredDate = qqlogin.expiredDate;
        self.avatarSmall = qqlogin.avatarSmall;
        self.avatarStandard = qqlogin.avatarStandard;
        self.nickName = qqlogin.nickName;
    }
}

5.释放该类


- (void)dispose
{
    self.accessToken = nil;
    self.openId = nil;
    self.expiredDate = nil;
    self.avatarSmall = nil;
    self.avatarStandard = nil;
    self.nickName = nil;
    [[NSFileManager defaultManager] removeItemAtPath:QQLoginFilePath error:nil];
    NSLog(@"QQ已退出登录");
}



对于归档路径,读者自定义


okay,五个步骤做完 了,读者如果有什么问题直接在下面问我,谢谢观看~!







你可能感兴趣的:(ios开发)