zoukankan      html  css  js  c++  java
  • 将Array、Dictionary等集合类的序列化和反序列化

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

    输出如下:

  • 相关阅读:
    [HDOJ3523]Image copy detection
    [HDOJ3526]Computer Assembling
    Ubuntu12.04 配置步骤
    const 详解
    ubuntu 12.04 源
    函数参数和数据成员同名
    友元
    静态数据 成员和静态函数
    成员指针
    内存泄露
  • 原文地址:https://www.cnblogs.com/mac_arthur/p/1699605.html
Copyright © 2011-2022 走看看