zoukankan      html  css  js  c++  java
  • objective-c 自定义归档

    基本概念

      自定义对象要支持归档,需要实现NSCoding协议

      NSCoding协议有两个方法,encodeWithCoder方法对对象的属性数据做编码处理,initWithCoder解码归档数据来初始化对象

      实现NSCoding协议后,就能通过NSKeyedArchiver归档

     

    实例代码:

    User.h

    1 #import <Foundation/Foundation.h>
    2 
    3 @interface User : NSObject<NSCoding>
    4 
    5 @property(nonatomic,copy)NSString *name;
    6 @property(nonatomic,copy)NSString *email;
    7 @property(nonatomic,assign)NSInteger age;
    8 
    9 @end

    User.m

    #import "User.h"
    #define AGE @"age"
    #define NAME @"name"
    #define EMAIL @"email"
    @implementation User
    
    //对属性编码,归档时调用
    - (void)encodeWithCoder:(NSCoder *)aCoder{
        [aCoder encodeInteger:_age forKey:AGE];
        [aCoder encodeObject:_name forKey:NAME];
        [aCoder encodeObject:_email forKey:EMAIL];
        
    }
    
    //对属性解码,解归档时调用
    - (id)initWithCoder:(NSCoder *)aDecoder{
        if (self = [super init]) {
            _age = [aDecoder decodeIntegerForKey:AGE];
            self.name = [aDecoder decodeObjectForKey:NAME];
            self.email = [aDecoder decodeObjectForKey:EMAIL];
        }
        return self;
    }
    
    
    @end

    main.m

    #import <Foundation/Foundation.h>
    #import "User.h"
    int main(int argc, const char * argv[])
    {
    
        @autoreleasepool {
            
            // insert code here...
            NSLog(@"Hello, World!");
            //归档
    //        User *user = [[User alloc] init];
    //        user.name = @"Warlock";
    //        user.email = @"warlock@wow.com";
    //        user.age = 1;
    //        
    //        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"user.txt"];
    //        if ([NSKeyedArchiver archiveRootObject:user toFile:path]){
    //            NSLog(@"创建成功");
    //        }
            
            //解归档
            NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"user.txt"];
            User *user = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
            NSLog(@"%@",user.name);
            
        }
        return 0;
    }

    先将  解归档  注释起来,运行归档,     然后注释 归档  ,在运行解归档

  • 相关阅读:
    了解HDD或SDD磁盘的健康状态
    修复丢失的打开方式
    Invoke-WebRequest : 请求被中止: 未能创建 SSL/TLS 安全通道。
    绕过禁止未登陆用户访问
    debug
    更新已有数据
    编码格式(乱码)
    ajax
    Http
    科学的管理和规范标准
  • 原文地址:https://www.cnblogs.com/mo-shou/p/3506963.html
Copyright © 2011-2022 走看看