一.定义对象:自定义对象必须遵从nscoding协议
@interface TestDic : NSObject
@property (nonatomic,copy) NSString *pro1;
@property (nonatomic,copy) NSString *pro2;
@implementation TestDic
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self=[super init]) {
self.pro1=[aDecoder decodeObjectForKey:@"pro1"];
self.pro2=[aDecoder decodeObjectForKey:@"pro2"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.pro1 forKey:@"pro1"];
[aCoder encodeObject:self.pro2 forKey:@"pro2"];
}
@end
二。使用NSKeyedArchived类和NSKeyedUnarchiver类实现存取
// 写文件
NSString *path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
// NSString *str=@"测试";
NSString *docpath=[path stringByAppendingPathComponent:@"test.data"];
NSDictionary *dic1=[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"pro1",@"2",@"pro2", nil];
NSDictionary *dic2=[NSDictionary dictionaryWithObjectsAndKeys:@"3",@"pro1",@"4",@"pro2", nil];
TestDic *test1=[[TestDic alloc]init];
TestDic *test2=[[TestDic alloc]init];
test1.pro1=[dic1 valueForKey:@"pro1"];
test2.pro1=[dic2 valueForKey:@"pro1"];
test1.pro2=[dic1 valueForKey:@"pro2"];
test2.pro2=[dic2 valueForKey:@"pro2"];
NSMutableArray *arr=[NSMutableArray array];
[arr addObject:test1];
[arr addObject:test2];
// NSData *imageData = [NSKeyedArchiver archivedDataWithRootObject:arr];
//NSArray *arr=[NSArray arrayWithObjects:@"1",@"2", nil];
BOOL iswrite= [NSKeyedArchiver archiveRootObject:arr toFile:docpath];
if (iswrite) {
NSLog(@"写入成功");
}else{
NSLog(@"写入失败");
}
NSLog(@"%@",docpath);
//读文件
NSMutableArray *mutablearr=[NSKeyedUnarchiver unarchiveObjectWithFile:docpath];
NSLog(@"%@",mutablearr);
网友评论