I've written a large social networking iPhone application, and one of the biggest issues I run into is the fact that NSInteger (and all the other NS-non-object types) are not first class citizens. This problem stems from the fact that, obviously, they have no representation for a nil value.
This creates two main problems:
One way to solve this is to use NSNumber all the time, but that gets extremely confusing. In a User model object, I would have about 20 different NSNumbers, and no easy way to tell if each one is a float, integer, bool, etc.
So here are my thoughts for potential solutions and the pros/cons. I'm not really sold on any of them, so I thought I'd ask for feedback and/or alternative solutions to this problem.
Looking for a convincing argument in favor of one of these techniques, or one I haven't thought of if you've got one.
UPDATE
I've gone ahead and started an open source project (Apache 2.0), into which I'll be pulling a number of our internal classes as I have time. It currently includes object wrappers for some of the more common native data types (BOOL, CGFloat, NSInteger, NSUInteger). We chose to do this because it upgrades these data types to first class citizens with strict typing. Maybe you disagree with this approach, but it has worked well for us, so feel free to use it if you want.
I'm adding other classes we've found uses for, including a disk-backed LRU cache, a "Pair" object, a low memory release pool, etc.
Enjoy github - Zoosk/ZSFoundation
The most common convention for representing the idea of nil
as an NSInteger
is to use the NSNotFound
value. This is, in fact, equal to NSIntegerMax
, though it tends to be more obvious to the reader that this is a sentinel value representing the lack of a number. There are many cases where this is used throughout Cocoa. One common case is as the location field of an NSRange
as a return value from -rangeOfString:
et al.
You could try this?
#define numberWithFloat(float f) \
[NSNumber numberWithFloat:f]
#define floatFromNumber(NSNumber *n) \
[n floatValue]
(see my original answer below)
Here's the other thing with NSNumber, you don't have to retrieve what you set.
For example
NSNumber *myInt = [NSNumber numberWithInteger:100];
float myFloat = [myInt floatValue];
is perfectly valid. NSNumber's strength is that it allows you to "weak-type" your primitives, use compare:
, use isEqualTo:
, and stringValue
for easy display.
[EDIT]
User @Dave DeLong says that sub-classing NSNumber is a Bad Idea
without much work. Since it's a class cluster (meaning NSNumber is an abstract superclass of a lot of subclasses) you'll have to declare your own storage if you sub-class it. Not recommended, and thanks to Dave for pointing that out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With