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

本文介绍如何使用Objective-C将集合类如NSArray和NSDictionary序列化到文件中,以及如何从文件中反序列化这些集合类。示例代码展示了如何保存和读取数组与字典。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.  

输出如下:

http://blog.prosight.me/index.php/2010/02/582

转载于:https://www.cnblogs.com/1208/archive/2012/07/05/2578210.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值