使用runtime完成解档归档

说明:解档归档需要遵守协议 NSCoding,并实现如下两个方法;

@implementation MyCookies
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (self) {
        
        /**runtime 的写法**/
        uint count;
        Ivar *ivars = class_copyIvarList([MyCookies class], &count);
        
        for (int i = 0; i < count; i ++) {
            Ivar ivar = ivars[i];
            NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
            [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
        }
        
        /***原始的写法
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.cookies = [aDecoder decodeObjectForKey:@"cookies"];
        self.array = [aDecoder decodeObjectForKey:@"array"];
        self.dictionary = [aDecoder decodeObjectForKey:@"dictionary"];
        */
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder{
    /**runtime 的写法*/
    uint count;
    
    Ivar *vars = class_copyIvarList([MyCookies class], &count);
    for (int i = 0; i < count; i ++) {
        Ivar ivar = vars[i];
        NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
        [aCoder encodeObject:[self valueForKey:key] forKey:key];
    }
/*
     原始写法
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.array forKey:@"array"];
    [aCoder encodeObject:self.cookies forKey:@"cookies"];
    [aCoder encodeObject:self.dictionary forKey:@"dictionary"];
 */
}

@end

现在就可以实现解挡和归档了

    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver =  [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:self.cookies forKey:@"myCookies"];
    [archiver finishEncoding];
    [data writeToFile:@"c://Path/mycookies" atomically:NO];
    
    NSData *readData = [NSData dataWithContentsOfFile:@"c://Path/mycookies"];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:readData];
    MyCookies *anothorCookies = [unarchiver decodeObjectForKey:@"myCookies"];
    anothorCookies.name = @"...";
    [unarchiver finishDecoding];

你可能感兴趣的:(使用runtime完成解档归档)