搜索
您的当前位置:首页正文

数据存储--归档篇

来源:二三娱乐
Plist
  • plist只能存储系统自带的一些常规的类,也就是有writeToFile方法的对象才可以使用plist保存数据。比如:字符串、、数组、字典、NSNumber、NSData....
偏好设置
  • 偏好设置是专门用来保存应用程序的配置信息的,一般情况不要再偏好设置中保存其他数据。如果利用系统的偏好设置来存储数据,默认就是存在Preferences文件夹下面的。偏好设置会将所有的数据保存到同一个文件中。偏好设置的本质其实就是Plist。


    偏好设置

归档的步骤:
在ViewController里保存Person对象
1.在ViewController的.m文件中

#import "ViewController.h"
#import "Person.h"

@interface ViewController ()
/**人*/
@property (nonatomic ,strong)Person *people;
/**路径*/
@property (nonatomic ,strong)NSString *path;
@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  //初始化数据
  [self initData];
 
}
-(void)initData
{
  //创建保存的对象
  Person *p = [[Person alloc]init];
  p.name = @"张三";
  p.age = 18;
  p.weight = 52.8;
  self.people = p;
  //保存路径
  NSString *dicPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
  self.path = [dicPath stringByAppendingPathComponent:@"people"];
}

- (IBAction)save:(UIButton *)sender {
  NSLog(@"path = %@",self.path);
    //将自定义对象保存到文件中
  [NSKeyedArchiver archiveRootObject:self.people toFile:self.path];
}
- (IBAction)unSave:(id)sender {
    // 2.从文件中读取对象
  Person *peo = [NSKeyedUnarchiver unarchiveObjectWithFile:self.path];
  NSLog(@"name = %@ age = %ld weight = %.2f",peo.name, peo.age ,peo.weight);
}```

 在Person.h中

import <Foundation/Foundation.h>

// 如果想将一个自定义对象保存到文件中必须实现NSCoding协议
@interface Person : NSObject<NSCoding>
/名字/
@property (nonatomic ,strong)NSString name;
/
年龄/
@property (nonatomic ,assign)NSInteger age;
/
体重/
@property (nonatomic ,assign)float weight;
@end```
在Person.m中

// 当将一个自定义对象保存到文件的时候就会调用该方法
// 在该方法中说明如何存储自定义对象的属性
// 也就说在该方法中说清楚存储自定义对象的哪些属性
- (void)encodeWithCoder:(NSCoder *)aCoder
{
  [aCoder encodeObject:self.name forKey:@"PersonName"];
  [aCoder encodeInteger:self.age forKey:@"PersonAge"];
  [aCoder encodeFloat:self.weight forKey:@"PersonWeight"];
}
// 当从文件中读取一个对象的时候就会调用该方法
// 在该方法中说明如何读取保存在文件中的对象
// 也就是说在该方法中说清楚怎么读取文件中的对象
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
{
  if (self = [super init]) {
   
    self.name = [aDecoder decodeObjectForKey:@"PersonName"];
    self.age = [aDecoder decodeIntegerForKey:@"PersonAge"];
    self.weight = [aDecoder decodeFloatForKey:@"PersonWeight"];
   
  }
  return self;
}```
Top