Object-C代码练习【自定义对象的归档】

//
//  main.m
//  自定义对象的归档
//
//  Created by on 14-11-9.
//  Copyright (c) 2014年 Apple. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "User.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        /*******归档*******/
        User *user = [[User alloc] init];
        user.name = @"Tom";
        user.email = @"aaa@cc.com";
        user.password = @"123";
        user.age = 22;
        
        NSString *filePath = @"/Users/wujiafeng/Desktop/archiver";
        BOOL success = [NSKeyedArchiver archiveRootObject:user toFile:filePath];
        
        if (success) {
            NSLog(@"归档成功");
        }
        
        
        /********解归档********/
        User *unUser = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        NSLog(@"%@", unUser);
    }
    return 0;
}


//
//  User.h
//  自定义对象的归档
//
//  Created by on 14-11-10.
//  Copyright (c) 2014年 Apple. 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) NSInteger age;

@end
//
//  User.m
//  自定义对象的归档
//
//  Created by on 14-11-10.
//  Copyright (c) 2014年 Apple. All rights reserved.
//

#import "User.h"

@implementation User

#define NAME @"name"
#define EMAIL @"email"
#define PASSWORD @"password"
#define AGE @"age"

// 对属性编码,归档时候会调用
- (void)encodeWithCoder:(NSCoder *)aCoder {
    NSLog(@"对属性编码");
    [aCoder encodeObject:_name forKey:NAME];
    [aCoder encodeObject:_email forKey:EMAIL];
    [aCoder encodeObject:_password forKey:PASSWORD];
    [aCoder encodeInteger:_age forKey:AGE];
}

// 对属性解码,解归档时会调用
- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        NSLog(@"对属性解码");
        _name = [aDecoder decodeObjectForKey:NAME];
        _email = [aDecoder decodeObjectForKey:EMAIL];
        _password = [aDecoder decodeObjectForKey:PASSWORD];
        _age = [aDecoder decodeIntegerForKey:AGE];
    }
    
    return self;
}

- (NSString *) description {
    NSString *str = [NSString stringWithFormat:@"name=%@, email=%@, password=%@, age=%ld", _name, _email, _password, _age];
    return str;
}

@end

转载于:https://my.oschina.net/are1OfBlog/blog/342618

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值