OC之自定义归档

//
//  main.m
//  自定义归档
//
//  Created by New-World on 13-11-5.
//  Copyright (c) 2013年 Gary. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "User.h"
int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        User *user=[User new];
        user.name=@"laoxu";
        user.email=@"xuchina67@163.com";
        user.age=22;
        user.password=@"123456";
        NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"test.plist"];
        BOOL success=[NSKeyedArchiver archiveRootObject:user toFile:path];
        if (success) {
            NSLog(@"归档成功!");
        }
        [user release];
        
        
        User *un_user=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSLog(@"%@",un_user);
    }
    return 0;
}

///
//
//  USer.h
//  自定义归档
//
//  Created by New-World on 13-11-5.
//  Copyright (c) 2013年 Gary. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface User : NSObject<NSCoding>

@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *email;
@property(nonatomic,copy)NSString *password;
@property(nonatomic,assign)int age;
@end
/
//
//  USer.m
//  自定义归档
//
//  Created by New-World on 13-11-5.
//  Copyright (c) 2013年 Gary. All rights reserved.
//

#import "User.h"
#define AGE @"age"
#define NAME @"name"
#define EMAIL @"email"
#define PASSWORD @"password"

@implementation User
//对属性进行编码,归档的时候调用
- (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];
        self.name=[aDecoder decodeObjectForKey:NAME];
        self.email=[aDecoder decodeObjectForKey:EMAIL];
        self.password=[aDecoder decodeObjectForKey:PASSWORD];
    }
    return self;
}
-(NSString *)description{//输出User时调用的方法
    NSString *str=[NSString stringWithFormat:@"\n age=%d \n name=%@ \n email=%@ \n password=%@",_age,_name,_email,_email];
    return str;
}


-(void)dealloc{
    [_name release];
    [_email release];
    [_password release];
    [super dealloc];
}
@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值