首页 > 其他 > 详细

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

时间:2015-09-26 00:15:35      阅读:353      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!