你的位置:首页 > 操作系统

[操作系统]NSCoder


person.h头文件内容

  1. #import <Foundation/Foundation.h>
  2. @interface Person : NSObject
  3. {
  4.     NSString *name;
  5.     char sex;
  6.     int age;
  7. }
  8. @property(nonatomic,copy) NSString *name;
  9. @property char sex;
  10. @property int age;
  11. @end

 

 person.m实现文件

  1. #import "Person.h"

 

  1. @implementation Person
  2. @synthesize name,age,gender;
  3. -(void)encodeWithCoder:(NSCoder *)aCoder
  4. {
  5.     
  6.     [aCoder encodeObject:name forKey:@"stuName"];
  7.     NSNumber *age1 = [NSNumber numberWithInt:age];
  8.     [aCoder encodeObject:age1 forKey:@"stuAge"];
  9.     NSNumber *gender1 = [NSNumber numberWithChar:gender];
  10.     [aCoder encodeObject:gender1 forKey:@"stuGender"];
  11. }
  12. -(id)initWithCoder:(NSCoder *)dCoder
  13. {
  14.     name = [dCoder decodeObjectForKey:@"stuName"];
  15.     age = [[dCoder decodeObjectForKey:@"stuAge"]intValue];
  16.     gender = [[dCoder decodeObjectForKey:@"stuGender"]charValue];
  17.     return self;
  18. }
  19. @end

 

 main.m测试文件

  1. #import <Foundation/Foundation.h>
  2. #import "Person.h"
  3. int main(int argc, const char * argv[]) {
  4.     @autoreleasepool {
  5.         Person *p1 = [[Person alloc]init];
  6.         p1.name = @"zhangsan";
  7.         p1.age = 22;
  8.         p1.gender = 'F';
  9.         Person *p2 = [Person new];
  10.         p2.name = @"lisi";
  11.         p2.age = 23;
  12.         p2.gender = 'M';
  13.         
  14.         NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:30];
  15.         
  16.         [dic setObject:p1 forKey:@"person1"];
  17.         [dic setObject:p2 forKey:@"person2"];
  18.         //把字典内容存入到文件中
  19.         if ([NSKeyedArchiver archiveRootObject:dic toFile:@"/Users/mac/Desktop/a.plist"] ) {
  20.             NSLog(@"chenggong");
  21.         }
  22.         
  23.         NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithCapacity:30];
  24.         //从文件中读取内容放入到字典中
  25.         dic2 = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/mac/Desktop/a.plist"];
  26.         NSEnumerator *enumerator = [dic2 objectEnumerator];
  27.         id obj;
  28.         //遍历字典内容
  29.         while (obj = [enumerator nextObject]) {
  30.             NSLog(@"name = %@,age = %i,gender = %c",[obj name],[obj age],[obj gender]);
  31.         }
  32.     }
  33.     return 0;
  34. }