I am trying to implement a generic number class. Basically my app needs to receive a string from the user and parse it to determine if its imperial (ft in fraction or any combo of these) or if its metric (m cm mm or any combo). My idea was to make Metric & Imperial classes, both of which are of a more generic type Number. Then the UI creates a Number object passing in the string to parse, and the number determines if it is metric or imperial. I see how it would work easy making 1 large number class that does this, but it seems like I should separate the metric and imperial classes from the standard interface (Number) since they will do much more then just parse the string.
So if I do Number *num = [[Number alloc] initWithString:someString];
I would get a subclass of Number that is specific to Imperial or Metric. This is really where I know something isn't making sense, but I'm not sure how to do it.
What would be a good way to handle this?
What do you think is wrong with your proposal?
What you want to do and how to solve it exactly matches a Cocoa concept called "class clusters", described in the Cocoa Fundamentals Guide. Apple uses this pattern all over the place in Foundation and AppKit.
I would create a subclass of NSFormatter to do the conversion between strings and objects of your custom class. That way, you can associate the formatter with UI controls and then they will automatically give you objects of the right type.
How you implement your actual numbers depends. For instance, you could have a generic number class called Length and subclasses called LinegthInInches and LengthInMetres (say). Or you could go with one class that has a property called units that tells you whether the units are feet or metres or whatever. Or you could have a protocol that defines the required methods that any object must implement to be considered one of your numbers. That way you could conceivably add a category to NSNumber to make it conform to your protocol.
I would probably go with the first option i.e. flattish class hierarchy with a subclass for each unit type. Your NSNumberFormatter subclass would decide which number subclass to return based on the string it is given and it would format its strings based on the class of the number it was given.
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