OC2

it2024-10-30  15

// // 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; }

 

转载于:https://www.cnblogs.com/0515offer/p/4598466.html

最新回复(0)