PList 数据解析

前言

  • Objective-C

    1
    NS_AVAILABLE(10_6, 4_0) @interface NSPropertyListSerialization : NSObject
  • 如果对象是 NSArray 或 NSDictionary 可以将对象保存到 Plist 文件中,当根据 NSDictionary 创建 Plist 时,NSDictionary 中的键必须都是 NSString 对象。数组中的元素或字典中的值可以是 NSString、NSArray、NSDictionary、NSData、NSDate 和 NSNumber 对象。

  • iOS 实现的序列化方式的两种:NSKeyedArchiver,NSPropertyListSerialization。在这两种序列化方式中,NSData 都是序列化的目标。两种方式的不同点在于 NSPropertyListSerialization 是针对数组和字典类型的,而 NSKeyedArchiver 是针对对象的。

1、Plist 数据解析

  • Objective-C

    • Plist 反序列化

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      NSData *plistData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"PListDataFile" ofType:@"plist"]];

      /*
      NSPropertyListImmutable = 0, 不可变
      NSPropertyListMutableContainers = 1, 容器可变
      NSPropertyListMutableContainersAndLeaves = 2 容器和叶子可变

      0 什么额外操作也不做

      NSPropertyListOpenStepFormat = 1, OpenStep 格式
      NSPropertyListXMLFormat_v1_0 = 100, XML 格式
      NSPropertyListBinaryFormat_v1_0 = 200 二进制 格式

      如果不需要格式传入 NULL,使用序列化之前的格式反序列化
      */

      id result = [NSPropertyListSerialization propertyListWithData:plistData options:0 format:NULL error:NULL];
    • Plist 序列化

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      NSArray *array = @[@"bei", @"jing", @"huan", @"ying", @"nin"];
      NSDictionary *dictionary = @{@"name":@"chen chao", @"age":@"18", @"info":@"Good Teacher"};

      /*
      NSPropertyListOpenStepFormat = 1, OpenStep 格式,不可用
      NSPropertyListXMLFormat_v1_0 = 100, XML 格式
      NSPropertyListBinaryFormat_v1_0 = 200 二进制 格式

      options 应该永久设置为 0
      */

      NSData *arrayPlistData = [NSPropertyListSerialization dataWithPropertyList:array
      format:NSPropertyListXMLFormat_v1_0
      options:0
      error:NULL];
      NSData *dictionaryPlistData = [NSPropertyListSerialization dataWithPropertyList:dictionary
      format:NSPropertyListXMLFormat_v1_0
      options:0
      error:NULL];
文章目录
  1. 1. 前言
  2. 2. 1、Plist 数据解析
隐藏目录