Published

Read and Write NSArray, NSDictionary and NSSet to a File

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).

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

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: