13.8 · UserDefaults surprises and FileManager essentials

The simplest storage is where many interview answers go wrong: what UserDefaults returns for a key that is not there, and the small rules for writing and replacing files.

Mental model. Know the defaults for missing values and the order of operations for files: write to a temporary file, then replace.

Small stores

UserDefaults behaviour and the FileManager basics.

  1. What does UserDefaults return for a key that is not set, how do registered defaults work, and what should and should not be stored there? 13.8.1 · L2
    The typed getters never fail: integer(forKey:) returns 0, bool(forKey:) returns false and double(forKey:) returns 0.0 for a missing key, so you cannot tell…
  2. What are the FileManager basics for saving a document: creating directories, replacing a file, and the resource values you set on it? 13.8.2 · L3
    Three small rules prevent most file bugs. First, the directory must exist: writing to …/missing/sub/file fails (the check reports a cocoa error, code 4, “no…

More in Persistence & data