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

xiaoxiao2021-02-28  62

#define encodeRuntime(A) \

\

unsigned int count = 0;\

Ivar *ivars = class_copyIvarList([A class], &count);\

for (int i = 0; i<count; i++)="" {\<="" p="">

Ivar ivar = ivars[i];\

const char *name = ivar_getName(ivar);\

NSString *key = [NSString stringWithUTF8String:name];\

id value = [self valueForKey:key];\

[encoder encodeObject:value forKey:key];\

}\

free(ivars);\

\

#define initCoderRuntime(A) \

\

if (self = [super init]) {\

unsigned int count = 0;\

Ivar *ivars = class_copyIvarList([A class], &count);\

for (int i = 0; i<count; i++)="" {\<="" p="">

Ivar ivar = ivars[i];\

const char *name = ivar_getName(ivar);\

NSString *key = [NSString stringWithUTF8String:name];\

id value = [decoder decodeObjectForKey:key];\

[self setValue:value forKey:key];\

}\

free(ivars);\

}\

return self;\

\

@implementation Person

- (void)encodeWithCoder:(NSCoder *)encoder

{

    encodeRuntime(Person)

}

- (id)initWithCoder:(NSCoder *)decoder

{

    initCoderRuntime(Person)

}

@end

转载请注明原文地址: https://www.6miu.com/read-2631816.html

最新回复(0)