- #pragma mark - NSCoding
- - (void)encodeWithCoder:(NSCoder *)aCoder {
- [aCoder encodeObject:_name forKey:kNameKey];
- [aCoder encodeInteger:_age forKey:kAgeKey];
- [aCoder encodeObject:_address forKey:kAddress];
- [aCoder encodeObject:_photo forKey:kPhotoKey];
- }
-
- - (id)initWithCoder:(NSCoder *)aDecoder {
- if (self = [super init]) {
- _name = [aDecoder decodeObjectForKey:kNameKey];
- _age = [aDecoder decodeIntegerForKey:kAgeKey];
- _address = [aDecoder decodeObjectForKey:kAddress];
- _photo = [aDecoder decodeObjectForKey:kPhotoKey];
- }
- return self;
- }
-
- #pragma mark - NSCoping
- - (id)copyWithZone:(NSZone *)zone {
- Archive *copy = [[[self class] allocWithZone:zone] init];
- copy.name = [self.name copyWithZone:zone];
- copy.age = self.age;
- copy.address = [self.address copyWithZone:zone];
- copy.photo = self.photo;
- return copy;
- }
- @end
-
- - (IBAction)save:(id)sender {
-
-
- NSString *name = @"小杨在玩iOS";
- NSInteger age = 22;
- NSString *address = @"你猜我在哪~";
- UIImage *photo = [UIImage imageNamed:@"loginman.jpg"];
-
- Archive *archivingData = [[Archive alloc] init];
- archivingData.name = name;
- archivingData.age = age;
- archivingData.address = address;
- archivingData.photo = photo;
-
-
- NSMutableData *data = [[NSMutableData alloc] init];
- NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
-
- [archiver encodeObject:archivingData forKey:kArchivingDataKey];
- 方法被调用
- [archiver finishEncoding];
-
- [data writeToFile:self.archivingFilePath atomically:YES];
- }
- //接档
- - (IBAction)loadArchive:(id)sender {
- NSData *data = [[NSMutableData alloc] initWithContentsOfFile:self.archivingFilePath];
- NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
-
-
- Archive *archivingData = [unarchiver decodeObjectForKey:kArchivingDataKey];
- [unarchiver finishDecoding];
-
-
- NSString *name = archivingData.name;
- NSInteger age = archivingData.age;
- NSString *address = archivingData.address;
- self.imageView.image = archivingData.photo;
- NSLog(@"%@||%d||%@",name,age,address);
- }
转自:http://www.cnblogs.com/ios8/p/ios-archive.html