OC2_使用系统协议

//
//  Dog.h
//  OC2_使用系统协议
//
//  Created by zhangxueming on 15/6/24.
//  Copyright (c) 2015年 zhangxueming. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Dog : NSObject <NSCoding>

@property (copy, nonatomic)NSString *name;
@property (assign, nonatomic)NSInteger age;

@end



//
//  Dog.m
//  OC2_使用系统协议
//
//  Created by zhangxueming on 15/6/24.
//  Copyright (c) 2015年 zhangxueming. All rights reserved.
//

#import "Dog.h"

@implementation Dog

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    //如果父类也遵守对应的协议,那么应该先调用父类的方法进行编码
    //[super encodeWithCoder:aCoder];
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
    //如果父类也遵守对应的协议,先调用父类的方法解码
    //self = [super initWithCoder:aDecoder];
    if (self = [super init]) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"name = %@ age = %li",_name, _age];
}
@end
//
//  main.m
//  OC2_使用系统协议
//
//  Created by zhangxueming on 15/6/24.
//  Copyright (c) 2015年 zhangxueming. All rights reserved.
//

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

int main(int argc, const char * argv[]) {
    @autoreleasepool {
#if 0
        Dog *xiaoBai = [[Dog alloc] init];
        xiaoBai.name = @"小白";
        xiaoBai.age = 12;
        
        BOOL ret = [NSKeyedArchiver archiveRootObject:xiaoBai toFile:@"/Users/zhangxueming/Desktop/Test/dog.txt"];
        if (ret) {
            NSLog(@"归档成功");
        }
        else
        {
            NSLog(@"归档失败");
        }
#else
       Dog *dog=[NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/zhangxueming/Desktop/Test/dog.txt"];
        if (dog) {
            NSLog(@"%@", dog);
        }
        
#endif
    }
    return 0;
}

 

posted @ 2015-06-24 19:14  sirzhang  阅读(286)  评论(0编辑  收藏  举报
AmazingCounters.com