前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >将Array、Dictionary等集合类的序列化和反序列化

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

作者头像
EltonZheng
发布2021-01-26 11:16:44
4100
发布2021-01-26 11:16:44
举报

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

代码语言:javascript
复制
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]); 
}

输出如下:


本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档