iOS 自动归解档

Posted 极客学伟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 自动归解档相关的知识,希望对你有一定的参考价值。

#pragma mark - 智能归解档
- (void)xw_decode:(NSCoder*)aDecoder 
    Class cls = [self class];
    while (cls && cls != [NSObject class]) 
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList(cls, &count);
        for (int i = 0; i < count; i++) 
            Ivar ivar = ivars[i];
            NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
            id value = [aDecoder decodeObjectForKey:key];
            if (value) 
                [self setValue:value forKey:key];
            
        
        free(ivars);
        cls = [cls superclass];
    


- (void)xw_encode:(NSCoder*)aCoder 
    Class cls = [self class];
    while (cls && cls != [NSObject class]) 
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList(cls, &count);
        for (int i = 0; i < count; i++) 
            Ivar ivar = ivars[i];
            NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
            id value = [self valueForKey:key];
            if (value) 
                [aCoder encodeObject:value forKey:key];
            
        
        free(ivars);
        cls = [cls superclass];
    

一个宏实现:

#pragma mark - 智能归解档
#define XWCodingImplementation \\
- (instancetype)initWithCoder:(NSCoder *)aDecoder\\
if(self == [super init])\\
[self xw_decode:aDecoder];\\
\\
return self;\\
\\
\\
- (void)encodeWithCoder:(NSCoder *)aCoder\\
[self xw_encode:aCoder];\\
\\
+ (BOOL)supportsSecureCoding \\
    return YES;\\

以上是关于iOS 自动归解档的主要内容,如果未能解决你的问题,请参考以下文章

第六十三篇runtime实现归解档

iOS 数据储存--归档

iOS 模块分解—「Runtime面试工作」看我就 🐒 了 ^_^.

ios 归档解档

iOS解档与归档

iOS---归档与解档