Read and Write NSArray, NSDictionary and NSSet to a File

查询地址:http://iosdevelopertips.com/data-file-management/read-and-write-nsarray-nsdictionary-and-nsset-to-a-file.html

With just a few lines of code, you can read/write collections to/from files. The code below shows examples for writing and reading both NSArray and NSDictionary objects, the same logic would apply to an NSSet (or other collection type).

The example below starts by populating both an array and dictionary, each using the Objective-C literal syntax. Read more about using NSArray literals andNSDictionary literals.

Read and Write Collections to File

The process is straightforward:

– Create the NSArray and NSDictionary objects
– Obtain the path to write/read the files (application Documents directory)
– Append filenames to path for each collection type
– Use the ‘writeToFile:’ method of each object to save contents to file

NSString  *arrayPath;
NSString  *dictPath;
NSArray *array = @[@"IPA", @"Pilsner", @"Stout"];
 
NSDictionary *dictionary = @{@"key1" : array,
                             @"key2" : @"Hops",
                             @"key3" : @"Malt",
                             @"key4" : @"Yeast" };
 
// Get path to documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
  NSUserDomainMask, YES);
 
if ([paths count] > 0)
{
  // Path to save array data
  arrayPath = [[paths objectAtIndex:0]
      stringByAppendingPathComponent:@"array.out"];
 
  // Path to save dictionary
  dictPath = [[paths objectAtIndex:0]
      stringByAppendingPathComponent:@"dict.out"];
 
  // Write array
  [array writeToFile:arrayPath atomically:YES];
 
  // Write dictionary
  [dictionary writeToFile:dictPath atomically:YES];
}

Read NSArray NSDictionary NSSet From File

The code to read back from the collections is equally as simple, using the methods arrayWithContentsOfFile: and dictionaryWithContentsOfFile: read from the file paths created previously to read the save data:

// Read both back into new NSArray and NSDictionary object
NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:arrayPath];
NSDictionary *dictFromFile = [NSDictionary dictionaryWithContentsOfFile:dictPath];
 
// Print the contents
for (NSString *element in arrayFromFile)
  NSLog(@"Beer: %@", element);
 
for (NSString *key in dictFromFile)
  NSLog(@"%@ : %@", key, [dictionary valueForKey:key]);

The output in the console window is below:

Beer: IPA
Beer: Pilsner
Beer: Stout
key1 : (
    IPA,
    Pilsner,
    Stout
)
key2 : Hops
key3 : Malt
key4 : Yeast
时间: 2024-10-14 23:25:24

Read and Write NSArray, NSDictionary and NSSet to a File的相关文章

[转]一些NSArray,NSDictionary,NSSet相关的算法知识

iOS编程当中的几个集合类:NSArray,NSDictionary,NSSet以及对应的Mutable版本,应该所有人都用过.只是简单使用的话,相信没人会用错,但要做到高效(时间复杂度)精确(业务准确性),还需要了解其中所隐藏的算法知识. 在项目当中使用集合类几乎是不可避免的,集合类的使用场景其实可以进行抽象的归类.大多数时候我们需要将若干个对象(object)暂时保存起来,以备后续的业务逻辑进行操作,「保存和操作」,或者说「存与取」,对应到计算机世界的术语就是读和写.最初保存的时候我们Ins

NSArray,NSDictionary,NSSet总结

-学习笔记,以备以后查询 ------干货分割线------------------- -NSArray 1.初始化.取值等基础操作 -NSArray 是不可变数组,一旦创建完成就不能够对数组进行,添加,删除等操作 NSArray * array = [[NSArray alloc] init]; NSArray * array1 = [NSArray                        arrayWithObjects:@"one",@"two",@&q

NSDictionary NSMutableDictionary NSSet NSMutableSet

//description只是返回了一个字符串 //    [person description]; //        //如果想要打印需要NSLog //    NSLog(@"%@", [person description]);         //打印一个对象,实质打印的是description返回的字符串,如果没有重写description方法,系统默认打印<类名:指针[CDATA[]]> //    NSLog(@"%@", person

Xcode4.4(LLVM4.0编译器)中NSArray, NSDictionary, NSNumber优化写法

Xcode4.4(LLVM4.0编译器)中NSArray, NSDictionary, NSNumber优化写法 从xcode4.4开始,LLVM4.0编译器为Objective-C添加一些新的特性.创建数组NSArray,字典NSDictionary, 数值对象NSNumber时,可以像NSString的初始化一样简单方便.妈妈再也不担心程序写得手发酸了. A.   NSArray 首先是非常常用的NSArray,NSMutableArray.NSArray是一个初始化后就固定的静态数组.如果

NSData NSDate NSString NSArray NSDictionary 相互转化

//    NSData  NSDate NSString NSArray NSDictionary json NSString *string = @"hello word"; NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; NSArray *array = [NSArray arrayWithObjects:@"1",@"2",@"3",nil

oc/object-c/ios哪种遍历NSArray/NSDictionary方式快?测试报告

做app的时候,总免不了要多次遍历数组或者字典.究竟哪种遍历方式比较快呢?我做了如下测试:首先定义测试用宏: ? 1 2 3 4 5 6 7 8 9 #define MULogTimeintervalBegin(INFO) NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];\ NSTimeInterval duration = 0;\ NSLog(@"MULogTimeintervalBegin:%@", IN

NSArray / NSDictionary 转 Json

在iOS开发中,网络数据转换是必不可少的,我们时常会用到NSArray / NSDictionary转化成Json字符串. 网上看到很多都是借助于第三方去转化,就个人而言,我认为三方的东西一方面增加了冗余度,另一方面时常更新,比较头疼. 仔细看看了苹果自带的json序列化解析器,苹果提供了字典和数组转化Json字符串的方法. NSDictionary * dict = [[NSDictionary alloc]initWithObjectsAndKeys:@"张三",@"na

NSData NSDate NSString NSArray NSDictionary 相互转换

// NSData NSDate NSString NSArray NSDictionary json NSString *string = @"hello word"; NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; NSArray *array = [NSArray arrayWithObjects:@"1",@"2",@"3",nil]; N

遍历NSArray, NSDictionary, NSSet的方法总结

1,for循环读取 1 NSArray: 2 NSArray *array = /*…*/ 3 for(int i=0; i<array.count; i++) 4 { 5 id object = array[i]; 6 // do sth 7 } 8 9 NSDictionary: 10 NSDictionary *dic = /*…*/ 11 NSArray *keys = [dic allKeys]; 12 for(int i=0; i<keys.count; i++) 13 { 14