Skip to content

Instantly share code, notes, and snippets.

@edwardean
Created July 19, 2017 02:13
Show Gist options
  • Save edwardean/56156f77821ba320963e496ce345abcd to your computer and use it in GitHub Desktop.
Save edwardean/56156f77821ba320963e496ce345abcd to your computer and use it in GitHub Desktop.
runtime decode & encode
- (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];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment