#import <Foundation/Foundation.h>
@interface Student : NSObject<NSCoding>
@property (nonatomic,retain) NSString *name;
@property (nonatomic,assign) NSInteger age;
@property (nonatomic,retain) NSData *data;
@end
#import "Student.h"
@implementation Student
- (void)dealloc
{
[_name release];
[super dealloc];
}
/ 归档 进行编码
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeObject:self.data forKey:@"data"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
self.data = [aDecoder decodeObjectForKey:@"data"];
}
return self;
}
@end
- (void)archive
{
#define kDocumentsPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
Student *student = [[Person alloc] init];
student.name = @"wangLong";
student.age = 18;
student.data = UIImagePNGRepresentation([UIImage imageNamed:@"shenJ.jpg"]);
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archive = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archive encodeObject:student forKey:@"student"];
[archive finishEncoding];
NSString *archivePath = [kDocumentsPath stringByAppendingPathComponent:@"saveStudent"];
NSLog(@"%@",archivePath);
[data writeToFile:archivePath atomically:YES];
[student release];
[archive release];
}
- (void)unarchive
{
NSString *archivePath = [kDocumentsPath stringByAppendingPathComponent:@"saveStudent"];
NSData *data = [NSData dataWithContentsOfFile:archivePath];
NSKeyedUnarchiver *afrinde = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
Student *student = [afrinde decodeObjectForKey:@"student"];
UIImage *image = [UIImage imageWithData:student.data];
NSLog(@"%@",student.name);
}