数据存取之归档

本文介绍了一个Objective-C实例,展示了如何通过自定义类实现对象的编码与解码,利用NSKeyedArchiver和NSKeyedUnarchiver进行文件的存取操作。通过具体的代码示例,详细讲解了如何将自定义对象存档为文件以及如何从文件中读取这些对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 - (IBAction)savebtn:(id)sender {

//    GYLPerson * p = [[GYLPerson alloc]init];

//    p.name = @"guoyule";

//    p.age = 24;

//    p.hight = 178.0f;

    GYLStudent * stu = [[GYLStudent alloc]init];

    stu.name = @"guoyule";

    stu.age = 24;

    stu.hight = 178.0f;

    stu.email = @"guoyulehit@icloud.com";


    


    //2.获取文件路径

    NSString * docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory , NSUserDomainMask , YES) lastObject];

    //尾加文件名

    NSString * path = [docPath stringByAppendingString:@"guoyule.arc"];

    NSLog(@"path = %@",path);

//    3.将自己定义的对象保存到文件中

    [NSKeyedArchiver archiveRootObject:stu toFile:path];

    

    


}


- (IBAction)readBtn:(id)sender {


    NSString * docPth = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask,YES) lastObject];

    NSString * path = [docPth stringByAppendingString:@"guoyule.arc"];

//    2.从文件中读取对象

    GYLStudent * guo = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

    NSLog(@"%@,%d,%.1f,%@",guo.name,guo.age,guo.hight,guo.email);


}




在使用继承的时候 一定要让父类使用    [super encodeWithCoder:aCoder];

@class GYLStudent,GYLPerson;

-(void)encodeWithCoder:(NSCoder *)aCoder

{

    [super encodeWithCoder:aCoder];

    NSLog(@"GYLStudent encodeWithCoder");

    [aCoder encodeObject:self.email forKey:@"email"];

    

}

-(id)initWithCoder:(NSCoder *)aDecoder

{

    if (self = [super initWithCoder:aDecoder]) {

        NSLog(@"GYLStudent initWithCoder");

        self.email = [aDecoder decodeObjectForKey:@"email"];

    }

    return self;

} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值