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

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 }

 

转载于:https://www.cnblogs.com/lxlmq412/p/4839785.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值