14 September 2009

NSUserDefaults Is Picky

If you’re not programming Mac or iPhone, you might want to skip this post…

I’m saving some state in an array, to be saved via NSUserDefaults. I know that NSArray can’t contain a nil value, but you can instead use [NSNull null]. BUT, property lists save only a limited number of classes, and NSNull is not one of them.

The confusing thing was that NSUserDefaults silently rejected an entire NSDictionary containing an NSArray containing an NSNull, while saving all the other changes I was making. So my testing showed that saving and restoring worked. And worked. And worked. Until the one case where there happened to be a nil. And then loading used the previous state.

So I had to come up with another way to save and restore a C array that can contain a nil. (In this case I was able to use a string.)

No comments: