Question

I saw this thread but wanted to confirm:

How to convert NSNumber objects for computational purposes?

So basically anytime you want to deal with these objects you have to unpack their ivars, and then pack them back up into new objects, presumably NSNumbers?

That seems hella weak(and a large pain in the backside, no?).

How do you folks work with these?

Do you avoid them? Subclass them? is there mutable versions?

This just seems like a lot of work to deal with them, would love to hear their benefits and ways more experienced programmers have used them, or what tactics they have used to avoid using them.

Thanks,

Nick

Was it helpful?

Solution

So basically anytime you want to deal with these objects you have to unpack their ivars, and then pack them back up into new objects, presumably NSNumbers?

Yes. (By the way calling doubleValue does not just mean unpack the ivar. There maybe some conversions too.)

That seems hella weak(and a large pain in the backside, no?).

This "boxing" is necessary because primitive numbers by themselves to not support Objective-C (Foundation.framework)'s ref-counting scheme. For example, you have to box a number as NSNumber in order to store them in an NSArray.

Do you avoid them?

You can't.

Subclass them?

You shouldn't, but if you have to, follow how it's suggested:

  • As with any class cluster, if you create a subclass of NSNumber, you have to override the primitive methods of its superclass, NSValue. Furthermore, there is a restricted set of return values that your implementation of the NSValue method objCType can return, in order to take advantage of the abstract implementations of the non-primitive methods. The valid return values are “c”, “C”, “s”, “S”, “i”, “I”, “l”, “L”, “q”, “Q”, “f”, and “d”.

If all you want is add some convenient methods e.g. -numberByAddingNumber:, use a category:

@implementation NSNumber (MyExtension)
-(NSNumber*)numberByAddingNumber:(NSNumber*)another {
   double myVal = [self doubleValue];
   double anotherVal = [another doubleValue];
   return [NSNumber numberWithDouble:myVal + anotherVal];
}
@end
...
NSNumber* a, *b;
...
NSNumber* c = [a numberByAddingNumber:b];
...

is there mutable versions?

No.

OTHER TIPS

I avoid NSNumbers when I'm going to have to perform arithmetic on a variable. Actually, I avoid them at all times, unless I'm going to be rolling them into Core Data or something.

Now that there are Objective-C Literals in the newest version of clang compiler (version 3.2 up, came with Xcode 4.6 and also can be built from source), you can do stuff like @42 and @(7+35) to "box" NSNumbers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top