Object-C 归档、解档

本文详细介绍了Objective-C中使用归档(NSKeyedArchiver)与解档(NSKeyedUnarchiver)进行对象存储与恢复的过程,包括如何在类中重写NSCoding协议以实现对象的归档与解档。

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

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

归档(NSKeyedArchiver)/解档(NSKeyedUnarchiver)

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

归档--》

NSArray *arr = [NSArray arrayWithObjects:@"one",@"two",@"three",nil];

NSMutableData * data = [NSMutableData data];

NSKeyedArchiver * arc = [NSKeyedArchiver alloc] initForWritingWithMutableData:data];


[arc encodeWithObjects:arr forKey:@"array"];

[arc encodeWithInt:100 forKey:@"age"];

[arc encodeWithObject:@"hello world" forKey:@"name"];


[arc finishEncoding];

[arc release];


NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"arc.txt"];

BOOL success = [data writeToFile:filePath atomically:YES];//success YES 归档成功

文件解档-------------》

NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"arc.txt"];

NSData * data = [[ NSData alloc] initWithContentsOfFile:path];

NSKeyedUnarchiver * unarc =[ [NSKeyedUnarchiver alloc] initForReadingWithData:data];


NSArray * arr = [unarc decodeObjectForKey:@"array"];

int age = [unarc decodeIntForKey:@"age"];

NSString *name = [unarc decodeObjectForKey:@"name"];


[data release];

[unarc release];

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

对象的归档、解档

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

类似java实现接口一样,OC实现NSCoding协议

重写两个方法:initWithCoder:NSCoder * 和 encodeWithCoder:NSCoder *

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

  self = [super init];

  if(self){

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

    self.age = [aDecoder decoderObjectForKey:@"age"];

    self.number = [aDecoder decoderObjectForKey:@"number"];

    

  }

return self;

}


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

[aCoder encodeObject:_name forKey:@"name"];

[aCoder encodeInteger:_age forKey:@"age"];

[aCoder encodeObject:_number forKey:@"number"];

}


Person *per = [[Person alloc] init];

per.name = @"hello";

per.age = 12;

per.number = @"10086";


NSString *path = [NSHomeDirectory stringByAppendingPathComponent:@"persion.plist"];

BOOL success = [NSKeyedArchiver archiveRootObject:per toFilePath:path];

 [per release];


//解档对象

 Person * per = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
















 


--》

解档


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值