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

Posted by Elton's Blog on February 15, 2010

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

NSArray *array = [NSArray arrayWithObjects: 
    @"Hefeweizen", @"IPA", @"Pilsner", @"Stout", nil];
 
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
  array, @"array", @"Stout", @"dark", @"Hefeweizen", @"wheat", @"IPA", 
  @"hoppy", nil];
 
// 得到documents directory的路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
  NSUserDomainMask, YES);
if ([paths count] > 0)
{
  // Array的保存路径
  NSString  *arrayPath = [[paths objectAtIndex:0] 
      stringByAppendingPathComponent:@"array.out"];
 
  // dictionary的保存路径
  NSString  *dictPath = [[paths objectAtIndex:0] 
      stringByAppendingPathComponent:@"dict.out"];
 
  // 保存array
  [array writeToFile:arrayPath atomically:YES];
 
  // 保存dictionary
  [dictionary writeToFile:dictPath atomically:YES];
 
  // 从文件中读取回来
  NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:arrayPath];
  NSDictionary *dictFromFile = [NSDictionary dictionaryWithContentsOfFile:dictPath];
 
  for (NSString *element in arrayFromFile) 
    NSLog(@"Beer: %@", element);
 
  for (NSString *key in dictFromFile) 
    NSLog(@"%@ Style: %@", key, [dictionary valueForKey:key]); 
}

输出如下: