iOS最基本的归档和解归档的用法:
main.m里面需要实现:
#import <Foundation/Foundation.h>
#import "Animal.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Animal *animal = [Animal new];
animal.name = @"hello animal_name";
animal.age = 22;
animal.height = 122;
animal.dog = [Dog new];
animal.dog.dogName = @"hello dog_name";
NSString *path = @"/Users/frankfan/Desktop/animalFile.plist";
/*归档--ios中数据持久化的一种方式*/
/*将OC中【内存】产生的对象/数据保存到磁盘上*/
/*归档的实际过程是将内存中的对象进行编码序列化,形成有一定组织结构的数据*/
// [NSKeyedArchiver archiveRootObject:animal toFile:path];
//解归档
Animal *resultAniaml = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"resultAnimal:%@",resultAniaml.dog.dogName);
}
return 0;
}
Animal.h里面需要实现:
#import <Foundation/Foundation.h>
#import "Dog.h"
@interface Animal : NSObject<NSCoding>
@property (nonatomic,strong)Dog *dog;
@property (nonatomic,copy)NSString *name;
@property (nonatomic,assign)int age;
@property (nonatomic,assign)float height;
@end
Animal.m里面需要实现:
#import "Animal.h"
#define kDOG @"kdog"
#define kNAME @"kname"
#define KAGE @"kage"
#define KHEIGHT @"kheight"
@implementation Animal
//解归档需要实现这个方法
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
_dog = [aDecoder decodeObjectForKey:kDOG];
_name = [aDecoder decodeObjectForKey:kNAME];
_age = [aDecoder decodeIntForKey:KAGE];
_height = [aDecoder decodeFloatForKey:KHEIGHT];
}
return self;
}
/*NSCoding中的方法,通过这个方法,我们将对象中的成员变量进行编码,key由我们自己定义,这个key是后续用来解归档所用的*/
//归档需要实现这个方法
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:kNAME];
[aCoder encodeInt:self.age forKey:KAGE];
[aCoder encodeFloat:self.height forKey:KHEIGHT]
;
//自定义对象归档,必须要实现NSCoding协议中的方法
[aCoder encodeObject:self.dog forKey:kDOG];
}
@end
Dog.h里面需要实现:
#import <Foundation/Foundation.h>
@interface Dog : NSObject<NSCoding>
@property (nonatomic,copy)NSString *dogName;
@end
Dog.m里面需要实现:
#import "Dog.h"
@implementation Dog
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
_dogName = [aDecoder decodeObjectForKey:@"kdogName"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.dogName forKey:@"kdogName"];
}
@end