As You Were

Devin Coughlin's blog.
Styles: Serious Spare

January 18, 2007

NSSet Theory

I found an interesting crasher today that essentially went like this:

NSSet *x = ...

. . .

x = [NSSet setWithObject:x];

This is bad for two reasons: 1) the set {x} violated the Foundation Axiom of ZFC and 2) it led to a stack overflow elsewhere in the program when I attempted to send -valueForKey: to each member of x.

This second bit led to an interesting, and very useful, discovery: sending -valueForKey: to an instance of NSSet will return a new set with the results of sending -valueForKey: to each each member of the first set. That is,

[[NSSet setWithObjects:@"Foo", @"Bar", nil] valueForKey:@"uppercaseString"]

returns the set {@"FOO", @"BAR"} and

[[NSSet setWithObjects:@"a", @"bb", @"ccc", nil] valueForKey:@"length"]

returns the set {1, 2, 3}.

So you can see why I was recursing infinitely above. This works analogously for NSArray.

And since today is self-referential day, I must recommend Tupper's Self-Referential Formula. (Via unto.net blog)

Posted by coughlin at 9:57 PM