【深入浅出ios开发】存储一般的数据对象

一般通过NSKeyedArchiver来存储一般的对象:

重点在encode和decode


存储数据:

[objc]  view plain copy
  1. - (IBAction)save:(id)sender {  
  2.     MrPerson *person = [[MrPerson alloc]init];  
  3.     person.name = @"Ranran";  
  4.     person.age = 16;  
  5.     person.height = 1.62;  
  6.     [NSKeyedArchiver archiveRootObject:person toFile:@"/Users/misaka/Desktop/0410/p.Data"];  
  7.       
  8. }  

读取数据:

[objc]  view plain copy
  1. - (IBAction)read:(id)sender {  
  2.       
  3.     MrPerson *person = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/misaka/Desktop/0410/p.Data"];  
  4.       
  5.     NSLog(@"%@---%ld-----%f",person.name,(long)person.age,person.height);  
  6.       
  7. }  

Person类头文件中的设置:

[objc]  view plain copy
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface MrPerson : NSObject<NSCoding>  
  4. @property (nonatomic,copy) NSString* name;  
  5. @property (nonatomic,assign) NSInteger age;  
  6. @property (nonatomic,assign) double height;  
  7. @end  

Person类实现文件中的设置:

[objc]  view plain copy
  1. #import "MrPerson.h"  
  2.   
  3. @implementation MrPerson  
  4. - (void)encodeWithCoder:(NSCoder *)aCoder  
  5. {  
  6.     [aCoder encodeObject:self.name forKey:@"name"];  
  7.     [aCoder encodeInteger:self.age forKey:@"age"];  
  8.     [aCoder encodeDouble:self.height forKey:@"height"];  
  9. }  
  10.   
  11. - (id)initWithCoder:(NSCoder *)aDecoder  
  12. {  
  13.     if (self = [super init]) {  
  14.      self.name =   [aDecoder decodeObjectForKey:@"name"];  
  15.      self.age  =   [aDecoder decodeIntegerForKey:@"age"];  
  16.      self.height =    [aDecoder decodeDoubleForKey:@"height"];  
  17.     }  
  18.     return self;  
  19. }  
  20. @end  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值