一.定義對象:自定義對象必須遵從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);