views:

461

answers:

3

I want to store in a NSMutableDictionary some null values using NSNull and then serialize this data using a property list. Problem is NSNull is not allowed and I get "Property list is in invalid format" error. Is there a workaround for this? Seems very surprising they didnt put NSNull on the list of valid plist objects.

Thanks, D

+2  A: 

No, there is no way to put NSNull in a property list. (Trivia: the binary property list format actually supports nulls, but the writer doesn’t implement support.)

For a dictionary, the easiest workaround is to simply filter out the null values, so { foo = "bar"; baz = null; } becomes { foo = "bar"; }.

Ahruman
Its not exactly the same thing as I need the null values to indicate that the key exists but has no corresponding values (i.e. I already know there is a key with no data as opposed to its a new key which I dont know about).
Perhaps you could serialise both A) a dictionary with just the keys which have a corresponding value, and B) an array of all the known keys, regardless of if they have data attached. Ultimately there is no way to put NSNull in a plist directly so you need to find a workaround.
Mike Abdullah
+2  A: 

From the documentation of NSPropertyListSerializationClass:

A property list object. plist must be a kind of NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary object. Container objects must also contain only these kinds of objects.

So you need to have one of those. Depending on the type of data, you could put in a placeholder instead of NSNull and then do a process before/after loading the .plist (like, for example, using a zero-length NSData object to represent your NSNull in the plist). Exactly what kind of placeholder would be dependent on what kind of data you are storing, and choosing something to avoid. Then, after loading, translate the empty NSData back to NSNull.

AlBlue
Seriously what is wrong with the apple programmers??? I hate having to write code like that.
DD, if what you want is general serialization, use NSCoder. Property lists have a fixed set of types, so no matter how far it’s expanded there will always be a need to convert something.
Ahruman
If you don't like the restrictions of the property lists (which can't support NSNull, as the documentation indicates) then don't use property lists. As the other commenter suggests, use your own serialisation format. NSPropertyList support != serialization.
AlBlue
+4  A: 

Instead of using a property list, consider using an NSKeyedArchiver and NSKeyedUnarchiver. Properties lists have a fixed set of types, and that doesn't include NSNull, and it isn't meant to be extended.

Here are links to the relevant documentation: NSCoding, NSKeyedArchiver and NSKeyedUnarchiver.

Jon Hess