码迷,mamicode.com
首页 > 其他好文 > 详细

Read and Write NSArray, NSDictionary and NSSet to a File

时间:2015-06-03 09:31:34      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:

查询地址: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

Read and Write NSArray, NSDictionary and NSSet to a File

标签:

原文地址:http://www.cnblogs.com/wvqusrtg/p/4548239.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!