• 热门专题

Objective-C OC中自定义对象的归档基本概念和使用方法(实现NSCoding协议)

作者:  发布日期:2014-02-14 21:20:08
Tag标签:Objective-C  自定义  对象  
  • 平时使用中,我们通常需要通过对自定义对象进行归档处理,自定义对象要进行归档,需要去实现NSCoding协议.

    NSCoding协议有两个方法,encodeWithCoder方法对对象的属性数据做编码处理。

    initWithCoder方法解码归档数据来进行初始化对象。


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

    下面来看下例子代码:

    Person.h头文件代码:

    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject <NSCoding>
    @property(nonatomic,copy)NSString *name;
    @property(nonatomic,copy)NSString *email;
    @property(nonatomic,copy)NSString *password;
    @property(nonatomic,assign)int age;
    @end
    Person.m实现代码:

    #import "Person.h"
    #define AGE @"age"
    #define NAME @"name"
    #define EMAIL @"email"
    #define PASSWORD @"password"
    @implementation Person
    //对对象属性进行编码方法
    - (void)encodeWithCoder:(NSCoder *)aCoder{
        [aCoder encodeInt:_age forKey:AGE];
        [aCoder encodeObject:_name forKey:NAME];
        [aCoder encodeObject:_email forKey:EMAIL];
        [aCoder encodeObject:_password forKey:PASSWORD];
    }
    //对对象属性进行解码方法
    - (id)initWithCoder:(NSCoder *)aDecoder{
        self=[super init];
        if (self!=nil) {
            _age=[aDecoder decodeIntForKey:AGE];
            _name=[[aDecoder decodeObjectForKey:NAME]copy];
            _email=[[aDecoder decodeObjectForKey:EMAIL]copy];
            _password=[[aDecoder decodeObjectForKey:PASSWORD]copy];
            
        }
        return self;
    }
    -(void)dealloc{
        [_name release];
        [_email release];
        [_password release];
        [super dealloc];
    }
    main.m函数代码:

    #import <Foundation/Foundation.h>
    #import "Person.h"
    int main(int argc, const char * argv[])
    {
    
        @autoreleasepool {
            Person *person=[[Person alloc]init];
            person.name=@"jack";
            person.age=20;
            person.email=@"jack@163.com";
            person.password=@"12345";
            NSString *homePath=NSHomeDirectory();
            NSString *srcPath=[homePath stringByAppendingPathComponent:@"Desktop/person.archiver"];
            BOOL success=[NSKeyedArchiver archiveRootObject:person toFile:srcPath];
            if (success) {
                NSLog(@"归档自定义对象成功.");
            }
            
            //还原数据
            Person *result= [NSKeyedUnarchiver unarchiveObjectWithFile:srcPath];
            NSLog(@"name=%@",result.name);
            NSLog(@"age=%d",result.age);
            NSLog(@"email=%@",result.email);
            NSLog(@"password=%@",result.password);
        }
        return 0;
    }
    运行截图:


About IT165 - 广告服务 - 隐私声明 - 版权申明 - 免责条款 - 网站地图 - 网友投稿 - 联系方式
本站内容来自于互联网,仅供用于网络技术学习,学习中请遵循相关法律法规