1.流程:
2.对象属性的"编码解码(类似kvc)":实现NSCoding协议的2个方法,归档、读取路径时自动调用。
-(void)encodeWithCoder:(NSCoder *)aCoder
-(id)initWithCoder:(NSCoder *)aDecoder
Student.h
#import <Foundation/Foundation.h> @interface Student : NSObject <NSCoding> { NSString *_name; int _age; } @property(nonatomic,retain)NSString *name; @property(nonatomic,assign)int age; @end
Student.m
#import "Student.h" @implementation Student @synthesize name = _name,age = _age; -(void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:_name forKey:@"name"]; [aCoder encodeInteger:_age forKey:@"age"]; } -(id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if (self) { self.name = [aDecoder decodeObjectForKey:@"name"]; self.age = [aDecoder decodeIntegerForKey:@"age"]; } return self; } @end
AppDelegate.m
NSArray *arr = [NSArray arrayWithObjects:@"one",@"two",@"three", nil]; //[arr writeToFile:PATH atomically:YES]; NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3", nil]; NSMutableData *mData = [[NSMutableData alloc]init]; //归档 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mData];//存档 [archiver encodeObject:arr forKey:@"arr"]; [archiver encodeObject:dic forKey:@"dic"]; [archiver finishEncoding]; [mData writeToFile:PATH atomically:YES];//写入路径 //解档 NSData *data = [NSData dataWithContentsOfFile:PATH];//读取路径 NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];//解档 NSDictionary *dictionary = [unarchiver decodeObjectForKey:@"dic"]; NSLog(@"%@",dictionary); //2.存对象属性 Student *s = [[Student alloc]init]; s.name = @"jobs"; s.age = 25; NSData * data1 = [NSKeyedArchiver archivedDataWithRootObject:s]; [data1 writeToFile:@"/Users/huen/Desktop/归档解档/p.rtf" atomically:YES]; NSData *data2 = [NSData dataWithContentsOfFile:@"/Users/huen/Desktop/归档解档/p.rtf"]; Student *stu = [NSKeyedUnarchiver unarchiveObjectWithData:data2]; NSLog(@"%@,%d",stu.name,stu.age);
原文:http://www.cnblogs.com/huen/p/3534604.html