Objective C - design advice: Class to store a bodyweight value

General Tech Learning Aids/Tools 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Learning Aids/Tools related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer 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?

profilepic.png
manpreet 2 years ago

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.


0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.