Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorthand way to get a float from an array?

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 ;)

like image 531
Pete McPhearson Avatar asked Jan 23 '12 12:01

Pete McPhearson


3 Answers

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];
like image 176
Stephen Darlington Avatar answered Sep 20 '22 05:09

Stephen Darlington


I don't think there is any shorthand for that, by the way

float myFloatValue = [[myArray objectAtIndex:i] floatValue];

is legal.

like image 43
X Slash Avatar answered Sep 19 '22 05:09

X Slash


Unfortunately Objective-C doesn't support Auto-Boxing.

For more info please visit to link -Aotoboxing in objective c?

like image 39
iOSPawan Avatar answered Sep 19 '22 05:09

iOSPawan