I'm a beginner with iPhone dev in Objective C and one thing I find I'm doing quite a lot is getting floats (and ints) in and out of various NSArrays
float myFloatValue = [(NSNumber *)[myArray objectAtIndex:integerSelector] floatValue];
I understand that I need to do this boxing because a float (or int) isn't a pointer and the NSArray accepts only pointers.
I'm just wondering if there a little bit of syntactic sugar to shorten this line of code - mostly because when I have a couple of arrays and I'm looping over them to do some processing I find that the lines start getting massive and I have to break out the lines that extract the number form the array just to make the code readable - then I have a lot of gumph lines that tend to make the logic harder to follow.
In a language like C# I would write something like
float myResult = myArray[i] + someOtherArray[i+1];
(ok - that's probably a pretty dumb line of code - but syntactically it's quite clean, I guess because .net is doing the boxing implicitly where I can't see it)
in objective C I find myself writing:
float myFloatValue = [(NSNumber *)[myArray objectAtIndex:i] floatValue];
float myOtherFloatValue = [(NSNumber *)[someOtherArray objectAtIndex:i+1] floatValue];
float myResult = myFloatValue + myOtherFloatValue;
I'm just wondering if I'm missing a trick here by typing it all out longhand. Should I be using an alternative to NSArray? Is there a shortcut for the boxing/unboxing?
Or I guess, should I just get used to it and stop whinging ;)
You can create a category:
@class NSArray (FloatHelper)
- (float) floatAtIndex:(NSUInteger)i;
@end
@implementation NSArray (FloatHelper)
- (float) floatAtIndex:(NSUInteger)i {
return [[self objectAtIndex:i] floatValue];
}
@end
(Untested and has no error handling, which, obviously, is not a good idea.)
Then it could be used as follows:
float a = [array floatAtIndex:1];
I don't think there is any shorthand for that, by the way
float myFloatValue = [[myArray objectAtIndex:i] floatValue];
is legal.
Unfortunately Objective-C doesn't support Auto-Boxing.
For more info please visit to link -Aotoboxing in objective c?
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