Elton's Blog

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

by Elton on 2010年02月15日, under iPhone

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.  

输出如下:

相关文章:

  1. NSArray 和 KVC
  2. 如何使用Objective-C解析HTML和XML
  3. Cocoa内存管理的简单规则[翻译]
  4. Objective-C中切分数组
  5. iPhone Table View 教程(2) 创建一个简单表格
:, , ,

3 Comments for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit my friends!

A few highly recommended friends...