No, don't not use NSNumber
at all, do not even add a category to it - this class (cluster) if designed for when you need to store a primitive type as an object and little else.
It you wish to encapsulate a weight write a class to do it, something along the lines of (code typed at terminal):
@interface Weight : NSObject
@property double kilos:
@property double pounds;
// etc
@end
@implementation Weight
{
double value; // stored in a suitable unit, kg, lb, oz, g, etc.
}
// implement getters and setters converting between unit of property and unit of value
// implement dependent property methods to setting, say, pounds produces a KVO
// notification for both pounds and kilos, etc. E.g.:
+ (NSSet *) keyPathsForValuesAffectingPounds
{
return [NSSet setWithObject:@"kilos"];
}
@end
Now you can set the value as one unit, read it as another, and get KVO notifications for all properties whenever one is set.
You'll want to add constructors (e.g. newWeightWithKilos:
), maybe operations (e.g. addWeight:
- which can just add the internal values), and need to decide whether a Weight
is mutable or immutable.
manpreet
Best Answer
2 years ago
As an aid to learning objective c/oop, I'm designing an iOS app to store periodic bodyweight measurements. I want to be able to retrieve the bodyweight in a variety of units (Kg, Lb, etc). For each bodyweight instance, can I/should I subclass NSNumber with a custom getter which return the weight in the correct unit? Perhaps I should simply subclass NSObject instead?