iOS归档与反归档

1、系统类的归档与反归档:

    NSString *pathDesktop =@"/Users/mac/Desktop(存储位置)";

    NSString *string =@"bei jing huan ying nin"; (系统类型)

    //+ (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path;

    //作用:将内存对象归档成归档文件

    [NSKeyedArchiverarchiveRootObject:string toFile:[pathDesktopstringByAppendingString:@"/归档文件string"]];

    //+ (id)unarchiveObjectWithFile:(NSString *)path;

    //作用:将归档文件反归档成内存中的对象

    NSString *stringFromFile = [NSKeyedUnarchiverunarchiveObjectWithFile:[pathDesktopstringByAppendingString:@"/归档文件string"]];

2、自定义类归档与反归档:

定义了一个Student类

//类声明的后面加上<协议名>表示该类遵守这个协议

@interface Student : NSObject <NSCoding>

@property (assign,nonatomic)int age;       

@property (copy,nonatomic)NSString *name; 

//协议中的方法//.h:中协议方法的声明可以省略

- (void)encodeWithCoder:(NSCoder *)aCoder;

- (id)initWithCoder:(NSCoder *)aDecoder;

@end


- (void)encodeWithCoder:(NSCoder *)aCoder{//归档的时候自动调用

    //- (void)encodeInt:(int)intv forKey:(NSString *)key;

    //作用:用来归档int类型的数据

    //intv:归档的int类型数据

    //key:归档的格式,任意,但是以什么格式归档就必须以什么格式反归档

    [aCoder encodeInt:_ageforKey:@"age"];

    //- (void)encodeObject:(id)objv forKey:(NSString *)key;

    //作用:用来归档oc对象

    [aCoder encodeObject:_nameforKey:@"name"];

}

- (id)initWithCoder:(NSCoder *)aDecoder{//反归档的时候自动调用

    //- (int)decodeIntForKey:(NSString *)key;

    //作用:按照归档格式反归档

    //key: 和归档时候指定的key对应

    _age = [aDecoderdecodeIntForKey:@"age"];    

    _name = [aDecoderdecodeObjectForKey:@"name"];

    

将自定义类归档与反归档

        NSString *pathDesktop =@"/Users/mac/Desktop";

        Student *std = [[Studentalloc] init];//实例化student对象

        std.age =19;

        std.name =@"zs";

        //归档student对象

        [NSKeyedArchiverarchiveRootObject:std toFile:[pathDesktopstringByAppendingString:@"/归档文件student"]];

        //反归档student对象

        Student *stdFromFile = [NSKeyedUnarchiverunarchiveObjectWithFile:[pathDesktopstringByAppendingString:@"/归档文件student"]];

    returnself;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值