Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize NSArray with floats?

Is this a valid way to initalize an NSArray with float objects?

NSArray *fatArray = [NSArray arrayWithObjects:
                    [NSNumber numberWithFloat:6.9],
                    [NSNumber numberWithFloat:4.7],
                    [NSNumber numberWithFloat:6.6],
                    [NSNumber numberWithFloat:6.9],nil];

It works and it feels right, just wanted to make sure I was on the right track.

gary

like image 738
fuzzygoat Avatar asked Oct 05 '09 09:10

fuzzygoat


3 Answers

As mouviciel already wrote, this is the way to do it. When I write something like this I usually make the code shorter using a simple macro:

#define FBOX(x) [NSNumber numberWithFloat:x]

Then you can rewrite the code like this:

NSArray *fatArray = [NSArray arrayWithObjects:
    FBOX(6.9), FBOX(4.7), FBOX(6.6), FBOX(6.9), nil];

Macros are evil, but in this case the macro is so simple I’d use it. Plus the code hurts a bit less to read, especially if the macro definition is not far.

If you wrote a lot code like this, you could create a category with a custom initializer with variable number of float arguments, but then there’s a problem ending the argument list. You could pass the total number of floats first:

- (id) initWithFloats: (int) numFloats data: (float) float1, ...;

But counting the arguments by hand is prone to error. Or you could use some sentinel value such as zero that would mark the end of the argument list, but this opens a whole new can of worms called floating-point comparison.


Please note that nowadays you can simply write the following:

NSArray *list = @[@6.9, @4.7, @6.6, @6.9];

It’s not a syntax dream come true, but it’s officially supported by the compiler and it’s much better than the previous solutions. See the documentation for more goodness.

like image 144
zoul Avatar answered Nov 03 '22 11:11

zoul


As far as I know, this is a perfectly valid way of putting floats in an NSArray.

like image 24
mouviciel Avatar answered Nov 03 '22 11:11

mouviciel


going off on a slight tangent, if all you want to do is store an array of floats and don't really need the added functionality of an NSArray or NSNumber, then you should also consider just a standard C array:

float fatArray[] = {6.6, 6.9, 4.7, 6.9};
like image 20
pxl Avatar answered Nov 03 '22 10:11

pxl