16

Among the settings that I am saving to NSUserDefaults is a non-mandatory object that doesn't make sense to have an out-of-the-box default. Until the user sets a value for this object, the app generates the error "[NSKeyedUnarchiver initForReadingWithData:]: data is NULL" when I unarchive from NSUserDefaults. I am ignoring the error and the app works fine otherwise.

Is there a best practice to avoid this, and is this a worry?

Michael Mangold
  • 1,741
  • 3
  • 18
  • 32
  • If you don't want a default value for that key, then just don't create the key in the first place. Only create it when the user sets the value. – rdelmar Jun 04 '13 at 22:23
  • But on app launch I don't know if a value had been set previously until I check NSUserDefaults. – Michael Mangold Jun 04 '13 at 22:37

1 Answers1

22

I'm not sure exactly what you're unarchiving, but if you can look at the keys first, before you unarchive, you could do it like this:

if ([[[NSUserDefaults standardUserDefaults] dictionaryRepresentation].allKeys containsObject:@"keyForNonMandatoryObject"]) {
        // unarchive the value here
    }
rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • 23
    Why not just do: `if ([[NSUserDefaults standardUserDefaults] objectForKey:@"keyForNonMandatoryObject"]) {`? Why get the whole dictionary just to check for one key? – rmaddy Jun 04 '13 at 23:26
  • Brilliant! That works great, and the solution offered by @maddy seams a bit more streamlined. Thanks. – Michael Mangold Jun 04 '13 at 23:54
  • @rmaddy, brain spazz I guess -- I was thinking I needed to avoid the object itself so he didn't get the error, but as you correctly suggest, just checking if that object exists won't get into the problem with trying to unarchive a non-existing object. – rdelmar Jun 05 '13 at 00:12
  • @rdelmar Please tell me what is "keyForNonMandatoryObject" here? is it a iOS default option for checking whether object available? Please help me in understanding this. – KishoreThindaak Mar 18 '15 at 07:24
  • @user2634244, no, that's just a string I made up for a key the OP would want to add later but not initially. It could have been anything. The answer is just checking if a certain key, "keyForNonMandatoryObject", exists. – rdelmar Mar 18 '15 at 15:22
  • @rmaddy @rdelmar I might be missing the obvious, but why would `if ([[NSUserDefaults standardUserDefaults] objectForKey:@"keyForNonMandatoryObject"])` **not** trigger unarchiving? – Johannes Fahrenkrug Aug 31 '16 at 13:43
  • @Johannes Why would it trigger unarchiving? All that call does is retrieve the object for the key which is an NSData object. – rmaddy Sep 01 '16 at 01:20
  • @rmaddy Oh, of course you are right. I think I misunderstood what OP tried to do. Correct me if I'm wrong: Was the OP (1) getting an object from NSUserDefaults, then (2) got back a NULL/nil value and then (3) without checking for nil passing that value to NSKeyedUnarchiver and that triggered the error? – Johannes Fahrenkrug Sep 01 '16 at 13:04