Question

Everyone knows that Foundation collections like NSArray, NSDictionary, and NSSet can't store nil objects, and that you have to use NSNull instead. I'm sure if I dug into the open-source Core Foundation source code, I could even find where that's enforced.

What I don't understand is, why are they designed this way? Is it purely because nil is used as a sentinel in some of their constructors, or is there a deeper reason for this behavior?

Was it helpful?

Solution

I don't think you'll get a satisfactory answer to this. It is just a design decision, like a thousand others that shaped Cocoa. Even if the people who originally made the decision back in the day were to show up and explain, the explanation would always necessarily boil down to "it's what seemed best to us". That is, it's clearly possible to design and implement collection classes that can hold nil and any justification for not supporting that is going to be contestable. Somebody will object that the justification doesn't make sense to them vs. the justification for doing it the other way. At that point it's just subjective judgment.

That said, here are a couple of issues:

  • Suppose [dict objectForKey:@"myKey"] returns nil. Is that because nil was added as the value for @"myKey" or because no value was added for that key?
  • Dictionaries and sets (and even NSArray methods like -containsObject: and -indexOfObject:) use -isEqual: to test object equality. However, [nil isEqual:anything] will always return false. Therefore, you'd never be able to find nil in the collection. You could overcome this with extra checks for nil, but that a) violates the design contract that -isEqual: is used to determine equality, and b) imposes implementation costs.
  • Methods like -lastObject, -firstObject, and -anyObject return nil when there are no objects in the collection. How do you distinguish that from returning a nil that's a member of the collection? Similarly, for -[NSEnumerator nextObject].
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top