iOS归档和解归档

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值