Lets break Cocoa - NSNumber edition

13 Jan 2014

I was inspired to break Cocoa by Mike Ash’s awesome post. Sometimes it’s more fun to break things than to build them.

So, lets break NSNumber.

NSNumber *one = [[NSNumber alloc] initWithInt:1];
NSNumber *zero = [[NSNumber alloc] initWithInt:0];
memcpy(zero, one, malloc_size(one));

This code does what is expected: copy the value pointed to by one to the value pointed to by zero.

However, any future invocations of [NSNumber numberWithInt:0], and [NSNumber alloc] initWithInt:0] will now return the instance that was returned by [NSNumber numberWithInt:1], and [[NSNumber alloc] initWithInt:1];

This works because NSNumber implements some values (including ints 1-12) as singletons. Using singletons is an interesting optimization - it would be wasteful to allocate new instances for commonly used values.

Published on 13 Jan 2014 Find me on Twitter!