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.