Note that there are some explanatory texts on larger screens.

plurals
  1. POHandling missing NSUserDefault keys after app updates
    text
    copied!<p>I've just got burned because an update to my iOS app went live on the App Store and unfortunately it crashes when using a new feature because of a bug in the way my code uses <code>NSUserDefaults</code>. My app uses <code>registerDefaults</code>, but the new feature tries to write to a key that doesn't exist after upgrading. It works fine if installing from scratch because the key gets created by <code>registerDefaults</code>.</p> <p>To be specific, my app uses nested dictionaries, so before the update the preferences file has this structure:</p> <pre><code>&lt;dict&gt; &lt;key&gt;Alpha&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Key&lt;/key&gt; &lt;string&gt;Value&lt;/string&gt; &lt;/dict&gt; &lt;key&gt;Beta&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Key&lt;/key&gt; &lt;string&gt;Value&lt;/string&gt; &lt;/dict&gt; &lt;key&gt;Charlie&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Key&lt;/key&gt; &lt;string&gt;Value&lt;/string&gt; &lt;/dict&gt; &lt;/dict&gt; </code></pre> <p>&mdash;and after the update, key <em>Delta</em> is required:</p> <pre><code>&lt;dict&gt; &lt;key&gt;Alpha&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Key&lt;/key&gt; &lt;string&gt;Value&lt;/string&gt; &lt;/dict&gt; &lt;key&gt;Beta&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Key&lt;/key&gt; &lt;string&gt;Value&lt;/string&gt; &lt;/dict&gt; &lt;key&gt;Charlie&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Key&lt;/key&gt; &lt;string&gt;Value&lt;/string&gt; &lt;/dict&gt; &lt;key&gt;Delta&lt;/key&gt; &lt;dict&gt; &lt;key&gt;Key&lt;/key&gt; &lt;string&gt;Value&lt;/string&gt; &lt;/dict&gt; &lt;/dict&gt; </code></pre> <p>My code is falling over when it tries to retrieve the dictionary for <em>Delta</em> from the user defaults in order to write some keys and values to it. For this scenario the dictionary is <code>nil</code> because after an update it's not in the preferences file.</p> <p>What's the best practice way to handle this situation? Should I simply check to see if the dictionary for <em>Delta</em> is <code>nil</code> before attempting to write to it and create it if required, or is there a less belt and braces approach?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload