Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 52 / 68

The basics of reading and writing files

This lesson covers reading and writing files in Objective-C, with the aim of saving and loading text from a program.

writeToFile:atomically:encoding:error: writes to a file and stringWithContentsOfFile:encoding:error: reads one. Saving configuration and logs makes this a basic everyday operation.

The sample code saves the contents of a memo with [content writeToFile:@"memo.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil] and reads the same file back with stringWithContentsOfFile:.

A common early stumble is specifying the encoding. Get the character encoding wrong and multi-byte text may not read or write correctly.

In professional work, combining this with handling for a missing file gives you far more robust file operations.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)