Rambo丶Q

导航

runtime学习实战一:类的属性进行归档解档

#import <Foundation/Foundation.h>

@interface PYPerson : NSObject

@property (nonatomic, assign) int age;

@property (nonatomic, assign) int height;

@property (nonatomic, copy) NSString *name;

@property (nonatomic, assign) int age2;

@property (nonatomic, assign) int height2;

@property (nonatomic, assign) int age3;

@property (nonatomic, assign) int height3;

@property (nonatomic, assign) int age4;

@property (nonatomic, assign) int height4;

@end

 

#import "PYPerson.h"

#import <objc/runtime.h>

 

@implementation PYPerson

- (instancetype)init {

    if (self = [super init]) {

        _age = 1;

        _height = 2;

        _name = @"name";

        _age2 = 3;

        _height2 = 4;

        _age3 = 5;

        _height3 = 6;

        _age4 = 7;

        _height4 = 8;

    }

    return self;

}

- (NSString *)description {

    return @"我是一个实例person";

}

- (void)encodeWithCoder:(NSCoder *)encoder {

    unsigned int count = 0;

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

    for (int i = 0; i<count; i++) {

        // 取出i位置对应的成员变量

        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);

}

 

- (id)initWithCoder:(NSCoder *)decoder {

    if (self = [super init]) {

        unsigned int count = 0;

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

        for (int i = 0; i<count; i++) {

            // 取出i位置对应的成员变量

            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

}

 

#import <Foundation/Foundation.h>

#import "PYPerson.h"

#import "APLProduct.h"

 

int main(int argc, const char * argv[]) {

    @autoreleasepool {

        // insert code here...

        NSLog(@"Hello, World!");

        PYPerson *person = [[PYPerson alloc] init];

        [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver                   archivedDataWithRootObject:person] forKey:@"person"];

        NSData *personData = [[NSUserDefaults standardUserDefaults] objectForKey:@"person"];

        if (personData != nil{

            PYPerson *tmpPerson = [NSKeyedUnarchiver unarchiveObjectWithData:personData];

            NSLog(@"%@", tmpPerson);

        }

    }

    return 0;

}

posted on 2015-08-13 16:34  Rambo丶Q  阅读(146)  评论(0编辑  收藏  举报