For the More Curious: Reading and Writing to the Filesystem

In addition to archiving and Data’s binary read and write methods, there are a few more methods for transferring data to and from the filesystem. One of them, Core Data, is coming up in Chapter 22. A couple others are worth mentioning here.

Using Data works well for binary data. For text data, String has two instance methods: write(to:atomically:encoding:) and init(contentsOf:encoding:). They are used as follows:

// Save someString to the filesystem do { try someString.write(to: someURL, atomically: true, encoding: .utf8) } catch { print("Error writing to URL: \(error)") } // Load someString from the filesystem do { let myEssay = try String(contentsOf: someURL, encoding: ...

Get iOS Programming: The Big Nerd Ranch Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.