OC 2_システムプロトコルを使う
7157 ワード
//
// 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;
}