码迷,mamicode.com
首页 > 其他好文 > 详细

6 归档解档(自定义对象数据存储)

时间:2015-09-26 00:17:42      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

1 #import <Foundation/Foundation.h>
2 
//记得要遵守<NSCoding>协议
> 3 @interface person : NSObject<NSCoding> 4 @property(nonatomic,copy)NSString *name; 5 @property(nonatomic,assign)int age; 6 @end
 1 #import "person.h"
 2 
 3 @implementation person
 4 -(void)encodeWithCoder:(NSCoder *)aCoder{
 5     [aCoder encodeObject:_name forKey:@"name"];
 6     [aCoder encodeInt:_age forKey:@"age"];
 7 }
 8 -(id)initWithCoder:(NSCoder *)aDecoder{
 9     if (self =[super init]) {
10         _name =[aDecoder decodeObjectForKey:@"name"];
11         _age =[aDecoder decodeIntForKey:@"age"];
12     }
13 
14     return self;
15 }
16 @end
1 #import <UIKit/UIKit.h>
2 
3 @interface ViewController : UIViewController
4 
5 
6 @end
 1 #import "ViewController.h"
 2 #import "person.h"
 3 @interface ViewController ()
 4 
 5 @end
 6 
 7 @implementation ViewController
 8 //存数据
 9 - (IBAction)save:(id)sender {
10     //获取临近的目录
11     NSString *tmpPath =NSTemporaryDirectory();
12     NSString *filePath =[tmpPath stringByAppendingPathComponent:@"person.data"];
13     person *p =[[person alloc] init];
14     p.name =@"天桥";
15     p.age =18;
16     [NSKeyedArchiver archiveRootObject:p toFile:filePath];
17 }
//取数据
18 - (IBAction)read:(id)sender { 19 NSString *tmpPath =NSTemporaryDirectory(); 20 NSString *filePath =[tmpPath stringByAppendingPathComponent:@"person.data"];
//记得给解档属性进行赋值
21 person * p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; 22 NSLog(@"%@,%d",p.name,p.age); 23 24 }

 

6 归档解档(自定义对象数据存储)

标签:

原文地址:http://www.cnblogs.com/lxlmq412/p/4839785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!