1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| #import "Dog.h" #import <objc/runtime.h> @interface Dog : NSObject<NSCoding> @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) int age; @property (nonatomic, assign) double height; @property (nonatomic, assign) double weight; @property (nonatomic, assign) double aaa; @property (nonatomic, assign) double bbb; @property (nonatomic, assign) double ccc; @end
#import "Dog.h" #import <objc/runtime.h> @implementation Dog
/* 这个数据的成员变量,不会被归档和解档 */ -(NSArray *)ignoredNames{ return @[@"_aaa",@"_bbb",@"_ccc"]; }
/// 从文件中读取对象时会调用这个方法(说明需要读取的属性) -(instancetype)initWithCoder:(NSCoder *)aDecoder{ if (self = [super init]) { //用来存储成员变量的数量 unsigned int outCount = 0; //获得Dog类的所有成员变量 Ivar *ivars = class_copyIvarList([self class], &outCount); // 遍历所有的成员变量 for (int i = 0; i < outCount; i++) { // 取出i位置对应的成员变量 Ivar ivar = ivars[i]; NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)]; //忽略解档对象 if ([[self ignoredNames] containsObject:key]) continue; //获得key对应的值 id value = [aDecoder decodeObjectForKey:key]; //设置到成员变量上 [self setValue:value forKeyPath:key]; } //释放内存 free(ivars);
} return self;
}
/// 将对象写入文件时会调用这个方法(说明哪个属性需要存储) -(void)encodeWithCoder:(NSCoder *)aCoder{ //用来存储成员变量的数量 unsigned int outCount = 0; //获得Dog类的所有成员变量 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)]; //忽略归档对象 if ([[self ignoredNames] containsObject:key]) continue; id value = [self valueForKeyPath:key]; [aCoder encodeObject:value forKey:key]; } //释放内存 free(ivars); }
//viewController点击方法 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ Dog *dog1 = [[Dog alloc]init]; dog1.age = 20; dog1.height = 1.55; dog1.name = @"wangcai"; dog1.weight = 50; //将dog归档到桌面 [NSKeyedArchiver archiveRootObject:dog1 toFile:@"/Users/Chenzhaoshen/Desktop/dog.hm"]; //解档 Dog *dog = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/Chenzhaoshen/Desktop/dog.hm"]; NSLog(@"%@,%d,%f,%f",dog.name,dog.age,dog.height,dog.weight); }
|