将Array、Dictionary等集合类的序列化和反序列化

来自:http://blog.prosight.me/index.php/tag/writetofile

Objective-C的集合类序列化到文件中或者从文件中反序列化其实很简单,请看下面的示例 代码:

  1.  
  2. NSArray *array = [NSArray arrayWithObjects:
  3.     @"Hefeweizen", @"IPA", @"Pilsner", @"Stout", nil];
  4.  
  5. NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
  6.   array, @"array", @"Stout", @"dark", @"Hefeweizen", @"wheat", @"IPA",
  7.   @"hoppy", nil];
  8.  
  9. // 得到documents directory的路径
  10. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
  11.   NSUserDomainMask, YES);
  12. if ([paths count] > 0)
  13. {
  14.   // Array的保存路径
  15.   NSString  *arrayPath = [[paths objectAtIndex:0]
  16.       stringByAppendingPathComponent:@"array.out"];
  17.  
  18.   // dictionary的保存路径
  19.   NSString  *dictPath = [[paths objectAtIndex:0]
  20.       stringByAppendingPathComponent:@"dict.out"];
  21.  
  22.   // 保存array
  23.   [array writeToFile:arrayPath atomically:YES];
  24.  
  25.   // 保存dictionary
  26.   [dictionary writeToFile:dictPath atomically:YES];
  27.  
  28.   // 从文件中读取回来
  29.   NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:arrayPath];
  30.   NSDictionary *dictFromFile = [NSDictionary dictionaryWithContentsOfFile:dictPath];
  31.  
  32.   for (NSString *element in arrayFromFile)
  33.     NSLog(@"Beer: %@", element);
  34.  
  35.   for (NSString *key in dictFromFile)
  36.     NSLog(@"%@ Style: %@", key, [dictionary valueForKey:key]);
  37. }
  38.  

输出如下:

原文地址:https://www.cnblogs.com/mac_arthur/p/1699605.html