• 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. }
  • 相关阅读:
    小程序购物车页面样式
    用css让div高度自动撑满屏幕
    客户端封装浏览器
    vuex模块的普通用法
    vue图片预览
    Django中Cookie和Session配置和操作
    jira的插件开发流程实践
    python3.7安装模块MySQLdb报错error: Microsoft Visual C++ 14.0 is required.
    Hadoop2.9下运行JAR包时System.out.println的输出日志
    MapReduce程序——WordCount(Windows_Eclipse + Ubuntu14.04_Hadoop2.9.0)
  • 原文地址:https://www.cnblogs.com/xjf125/p/4749749.html
Copyright © 2020-2023  润新知