數據存儲--歸檔篇

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;
}```
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容