views:

202

answers:

4

Hey stackfolk,

I'm working in the IPhone SDK, and am pretty new to objective-c. Right now I'm working with NSUserDefaults to save and restore setting on my IPhone app. In order to save the classes that have been created, I encode them into dictionary form, and then save the NSdictionary.

My problem is that I can't find a reasonable way to store a non-value (I.E. a class variable that is nil) in the dictionary in a reasonable way. To be more specific, lets say I have a class "Dog" and it's got NSString *tail-color. Lets say I'm trying to save a class instance of a dog without a tail, so tail-color for that instance is nil. What is a reasonable way of saving dog as a dictionary? It won't let me save nil into the NSdictionary. @"" isn't good, because if I do if(@""), @"" is true. I would like it to be false like nil.

I hope my question makes sense, and thanks for your help!

+4  A: 

You can use NSNull. Instantiate it like this:

[NSNull null]

I would recommend Archiving to save and restore your objects, however.

Zydeco
I tried that, it won't let my NSString* be [NSNull null]. It says "Comparison of distinct objective-c types lacks a cast"
Ethan
Yes, NSNull is used to represent nil values in collection types, but then you must deal with it appropiately. That's why I recommend archiving.
Zydeco
Oh man, I completely missed that. That's perfect! Thanks!
Ethan
+6  A: 

If you don't store anything for that key, nil will be returned when you call objectForKey:. If you check for nil when reading the data in, would that be enough? Optionally, you can use objectsForKeys:notFoundMarker: that will return a default value instead of nil.

So, store nothing at all in the dictionary for a value you don't have, and use a strategy for handling that value missing when reading.

You could use NSNull, but that doesn't feel standard, IMO.

MarkPowell
This is a good idea, but some of my objects are arrays with nil as one of the objects. I wouldn't be able to make an array that's missing a certain index, unfortunately.
Ethan
@Ethan: In the unlikely case that you really need `nil` in an array consider using `NSNull`, C arrays or CFArray. It looks like you haven't yet really absorbed the Cocoa way of doing things.
Georg
+1  A: 

You should use NSNull to represent nil objects in collections

Phil Nash
A: 

The best solution is to not save the values which are 'nil' in your case. While reading if the value is not present for your given key the dictionary will return you 'nil'.

Shreekara
Yeah, i may have to just use @"" and just check for it. I still think it's pretty stupid. I'm becoming less and less of a fan of objective C.
Ethan
No, don't save an empty string into the dictionary. Don't save any value at all. To save: `if (tailColor != nil) [dict setObject:tailColor forKey:@"TailColor"];` To load: `tailColor = [dict objectForKey:@"TailColor"];` It's simple.
benzado