实现NSCoding的自动归档和自动解档

原理

通过以下方法获取类的所有属性,然后进行保存和读取的操作

func class_copyIvarList(_ cls: AnyClass?, _ outCount: UnsafeMutablePointer<UInt32>?) -> UnsafeMutablePointer<Ivar>?

代码实现

代码为CSDN博主「番薯大佬」的原创文章,遵循 CC 4.0 BY-SA 版权协议
原文链接:https://blog.csdn.net/potato512/article/details/80947946
.h

@interface Person : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@property (nonatomic, strong) NSString *address;
@property (nonatomic, strong) NSString *company;
@property (nonatomic, strong) NSString *job;

@end

.m

#import "Person.h"
#import <objc/runtime.h>

@implementation Person

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init])
    {
        unsigned int outCount;
        Ivar *ivars = class_copyIvarList([self class], &outCount);
        for (int i = 0; i < outCount; i ++)
        {
            Ivar ivar = ivars[i];
            NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
            [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
        }
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    unsigned int outCount;
    Ivar *ivars = class_copyIvarList([self class], &outCount);
    for (int i = 0; i < outCount; i ++)
    {
        Ivar ivar = ivars[i];
        NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
        [aCoder encodeObject:[self valueForKey:key] forKey:key];
    }
}

@end


// 自动归档/解档
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"PersonInfo"];
if (data) {
        // 解档使用
        Person *person = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        NSLog(@"name: %@", person.name);
} else {
        Person *person = [Person new];
        person.name = @"devZhang";
        person.age = @(35);
        person.company = @"ShengXue";
        person.job = @"iOSDev";
        person.address = @"龙岗坂田国际中心";
        // 归档存储
        data = [NSKeyedArchiver archivedDataWithRootObject:person];
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"PersonInfo"];
}

推荐阅读更多精彩内容