TA的每日心情 | 汗 2024-10-15 10:05 |
---|
签到天数: 372 天 [LV.9]以坛为家II
|
1、对象进行归档操作时需要用到协议NSCoding,前面已经有讲到存档与解档操作,这里引进协议的概念,在协议中实现归档
2、创建一个类Person
3、在Person中使用协议NSCoding来实现存档操作
4、在implemetation中实现协议NSCoding的两个方法(必须实现)
5、对象person1归档到data中,data1将解档data;
6、创建person对象,将data1解档的数据赋值给person
Person.h- //
- // Person.h
- // NSCoding
- //
- // Created by yusian on 14-1-21.
- // Copyright (c) 2014年 yusian. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- @interface Person : NSObject <NSCoding>
- @property (retain) NSString * name;
- @property int age;
- @property (retain) Person * child;
- @end
复制代码 Person.m- //
- // Person.m
- // NSCoding
- //
- // Created by yusian on 14-1-21.
- // Copyright (c) 2014年 yusian. All rights reserved.
- //
- #import "Person.h"
- @implementation Person
- - (void)encodeWithCoder:(NSCoder *)aCoder {
- [aCoder encodeObject:_name forKey:@"name"];
- [aCoder encodeInt:_age forKey:@"age"];
- [aCoder encodeObject:_child forKey:@"chile"];
- }
- - (id)initWithCoder:(NSCoder *)aDecoder {
- if (self = [super init]) {
- self.age = [aDecoder decodeIntForKey:@"age"];
- self.name = [aDecoder decodeObjectForKey:@"name"];
- self.child = [aDecoder decodeObjectForKey:@"chile"];
- }
- return self;
- }
- @end
复制代码 main.m- //
- // main.m
- // NSCoding
- //
- // Created by yusian on 14-1-21.
- // Copyright (c) 2014年 yusian. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- #import "Person.h"
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
-
- Person * person1 = [[Person alloc] init];
- Person * person2 = [[Person alloc] init];
-
- person1.age = 30;
- person1.name = @"deny";
- person1.child = person2;
-
- NSData * data = [NSKeyedArchiver archivedDataWithRootObject:person1];
- [data writeToFile:@"/tmp/file.plist" atomically:YES];
-
- NSData * data1 = [NSData dataWithContentsOfFile:@"/tmp/file.plist"];
- Person * person = [NSKeyedUnarchiver unarchiveObjectWithData:data1];
-
- NSLog(@"Person %@ age is %d",person.name, person.age);
-
- }
- return 0;
- }
复制代码 输出结果:- 2014-01-21 22:46:20.541 NSCoding[2287:303] Person deny age is 30
- Program ended with exit code: 0
复制代码
|
|