• 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;
    }
  • 相关阅读:
    洛谷 1842 [USACO05NOV]奶牛玩杂技【贪心】
    洛谷 1757 通天之分组背包【分组背包】
    洛谷 1330 封锁阳光大学
    洛谷 1019 单词接龙
    【模板】CDQ分治
    BZOJ 2734 洛谷 3226 [HNOI2012]集合选数【状压DP】【思维题】
    BZOJ 2457 [BeiJing2011]双端队列
    洛谷 2015 二叉苹果树
    牛客网 牛可乐发红包脱单ACM赛 C题 区区区间间间
    牛客网 牛可乐发红包脱单ACM赛 B题 小a的旅行计划
  • 原文地址:https://www.cnblogs.com/0515offer/p/4598466.html
Copyright © 2020-2023  润新知