person.h头文件内容
- #import <Foundation/Foundation.h>
- @interface Person : NSObject
- {
- NSString *name;
- char sex;
- int age;
- }
- @property(nonatomic,copy) NSString *name;
- @property char sex;
- @property int age;
- @end
person.m实现文件
- #import "Person.h"
- @implementation Person
- @synthesize name,age,gender;
- -(void)encodeWithCoder:(NSCoder *)aCoder
- {
- [aCoder encodeObject:name forKey:@"stuName"];
- NSNumber *age1 = [NSNumber numberWithInt:age];
- [aCoder encodeObject:age1 forKey:@"stuAge"];
- NSNumber *gender1 = [NSNumber numberWithChar:gender];
- [aCoder encodeObject:gender1 forKey:@"stuGender"];
- }
- -(id)initWithCoder:(NSCoder *)dCoder
- {
- name = [dCoder decodeObjectForKey:@"stuName"];
- age = [[dCoder decodeObjectForKey:@"stuAge"]intValue];
- gender = [[dCoder decodeObjectForKey:@"stuGender"]charValue];
- return self;
- }
- @end
main.m测试文件
- #import <Foundation/Foundation.h>
- #import "Person.h"
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- Person *p1 = [[Person alloc]init];
- p1.name = @"zhangsan";
- p1.age = 22;
- p1.gender = 'F';
- Person *p2 = [Person new];
- p2.name = @"lisi";
- p2.age = 23;
- p2.gender = 'M';
- NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:30];
- [dic setObject:p1 forKey:@"person1"];
- [dic setObject:p2 forKey:@"person2"];
- //把字典内容存入到文件中
- if ([NSKeyedArchiver archiveRootObject:dic toFile:@"/Users/mac/Desktop/a.plist"] ) {
- NSLog(@"chenggong");
- }
- NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithCapacity:30];
- //从文件中读取内容放入到字典中
- dic2 = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/mac/Desktop/a.plist"];
- NSEnumerator *enumerator = [dic2 objectEnumerator];
- id obj;
- //遍历字典内容
- while (obj = [enumerator nextObject]) {
- NSLog(@"name = %@,age = %i,gender = %c",[obj name],[obj age],[obj gender]);
- }
- }
- return 0;
- }