标签:
Student.h
#import <Foundation/Foundation.h> @interface Student : NSObject<NSCoding> @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) int ID; @end
Student.m
#import "Student.h" @implementation Student //归档 - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:_name forKey:@"name"]; [aCoder encodeInt:_ID forKey:@"ID"]; } //解归档 - (id)initWithCoder:(NSCoder *)aDecoder { _name = [aDecoder decodeObjectForKey:@"name"]; _ID = [aDecoder decodeIntForKey:@"ID"]; return self; } @end
main
#import <Foundation/Foundation.h> #import "Student.h" #define PATH @"/Users/aoyolo5/Desktop/keyedArchiver" #define PATH2 @"/Users/aoyolo5/Desktop/StudenArchiver" int main(int argc, const char * argv[]) { @autoreleasepool { //数据持久化:归档(可以存储自定义类的对象,还可以加密) NSArray *array = @[@"1",@"2",@"3"]; // //归档(内容是加密过的) [NSKeyedArchiver archiveRootObject:array toFile:PATH]; // // //解归档 NSArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:PATH]; // NSLog(@"%@",array2); //NSMutableData 归档 //1.创建NSKeyedArchiver对象 NSMutableData *mData = [[NSMutableData alloc]initWithCapacity:10]; NSKeyedArchiver *keyArchiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mData]; //2.重复归档 [keyArchiver encodeObject:@"张峰的个人信息" forKey:@"10001"]; [keyArchiver encodeObject:array forKey:@"array"]; //3.结束归档 [keyArchiver finishEncoding]; //4.NSMutableData存入当文件 [mData writeToFile:PATH atomically:YES]; //NSMutableData 解归档 //1. NSMutableData *mData2 = [[NSMutableData alloc]initWithContentsOfFile:PATH]; //2.解归档对象 NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:mData2]; NSString *str = [unArchiver decodeObjectForKey:@"10001"]; NSLog(@"%@",str); NSArray *array3 = [unArchiver decodeObjectForKey:@"array"]; NSLog(@"%@",array3); //归档自定义对象 //对象必须遵循NSCoding协议,并且要实现协议中的方法 Student *stu = [[Student alloc]init]; stu.name = @"胡命淘"; stu.ID = 150401; [NSKeyedArchiver archiveRootObject:stu toFile:PATH2]; Student *stu2 = [NSKeyedUnarchiver unarchiveObjectWithFile:PATH2]; NSLog(@"%@ %d",stu2.name,stu2.ID); } return 0; }
标签:
原文地址:http://www.cnblogs.com/sunbinboke/p/4743276.html