Reputation: 185
I'm pretty new to iOS development, and I want to figure out if there's a good way to handle this issue. Basically, I'm making a technical calculator that returns some product specifications based on user input parameters. The product in question has specs for some, but not all user parameters, so I . In a constants file, I have a bunch of ATTEN_SPEC_X variables which are const double
or const NSString *
. Now, it's perfectly okay to be missing a spec, so my plan was to leverage NSArray's ability to hold different types and use introspection later to handle strings vs doubles before I report the returned specs.
Here's an incomplete example of one method I'm implementing. It's just a big conditional tree that should return a two-element array of the final values of spec
and nominal
.
- (NSArray *)attenuatorSwitching:(double *)attenuator{
double spec, nominal;
{...}
else if (*attenuator==0){
spec=ATTEN_SPEC_3; //this atten spec is a string!
nominal=ATTEN_NOM_3;
}
{...}
return {array of spec, nominal} //not actual obj-c code
So instead of making spec and nominal doubles, can I make them some other general type? The really important thing here is that I don't want to use any special handling within this method; another coder should be able to go back to the constants file, change ATTEN_NOM_3 to a double, and not have to retool this method at all.
Thanks.
Upvotes: 0
Views: 95
Reputation: 60110
The problem you'll run into is that NSArrays can't directly handle double
s. However, you can get around this if you start using NSNumber instances instead - you can return an NSArray *
containing an NSString *
and an NSNumber *
with no problems. If you need even more general typing, the Objective-C type id
can be used for any object instance (though still not with primitives; you can't make a double
an id
).
Later, when you get an array, you can use the NSObject method -isKindOfClass:
to determine the type of object you're pulling out of the array, and deal with the string or number depending on the resultant type. If you need to convert your NSNumber back to a double, just use the NSNumber instance method -doubleValue
to unbox your double. (+[NSNumber numberWithDouble:]
goes the other way, giving you an NSNumber out of a double.)
If you're using a recent enough version of Xcode, you can even make these things literals, rather than having to litter calls to +numberWithDouble:
all over the place:
return @[ @3, @"number of things" ]
Upvotes: 3