来自: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.  

输出如下:

 

posted on 2010-03-29 14:54  mac Arthur  阅读(894)  评论(0编辑  收藏  举报