Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of floating point values in Objective-C

How can I create array of floating point numbers in Objective-C? Is it possible?

like image 375
Dev Avatar asked Oct 17 '12 09:10

Dev


1 Answers

You can create a dynamic array (size decided at runtime, not compile time) in different ways, depending on the language you wish to use:

Objective-C

NSArray *array = [[NSArray alloc] initWithObjects:
    [NSNumber numberWithFloat:1.0f],
    [NSNumber numberWithFloat:2.0f],
    [NSNumber numberWithFloat:3.0f],
    nil];
...
[array release];    // If you aren't using ARC

or, if you want to change it after creating it, use an NSMutableArray:

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];
[array addObject:[NSNumber numberWithFloat:1.0f]];
[array addObject:[NSNumber numberWithFloat:2.0f]];
[array addObject:[NSNumber numberWithFloat:3.0f]];
...
[array replaceObjectAtIndex:1 withObject:[NSNumber numberWithFloat:99.9f]];
...
[array release];    // If you aren't using ARC

Or using the new-ish Objective-C literals syntax:

NSArray *array = @[ @1.0f, @2.0f, @3.0f ];
...
[array release];    // If you aren't using ARC

C

float *array = (float *)malloc(sizeof(float) * 3);
array[0] = 1.0f;
array[1] = 2.0f;
array[2] = 3.0f;
...
free(array);

C++ / Objective-C++

std::vector<float> array;
array[0] = 1.0f;
array[1] = 2.0f;
array[2] = 3.0f;
like image 54
trojanfoe Avatar answered Oct 19 '22 09:10

trojanfoe