Search code examples
objective-cnsarraynsnumber

How to make an array of numbers? (Objective-C)


I was trying to make an array of numbers. I need to call every element of this array. (array[i] ). I have done it like this:

NSNumber *array[] = {@0.240128f , @0.240128f , @0.953934f , @1.181351f, @1.382523f, @1.497086f, @1.437790f , @0.851196f};

but when I am calling this array it gives me an error:

Expected method to read array element not found on object of type "NSNumber"

Additional code moved from a comment:

int SIZE = 97;
fftw_complex *data, *fft_result, *ifft_result;
fftw_plan     plan_forward, plan_backward;
int           i;
NSArray * array = @[@0.240128f , @0.240128f , @0.953934f , @1.181351f, @1.382523f, @1.497086f, @1.437790f , @0.851196f];

float a0 = [array[0] floatValue];
data = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * SIZE);
fft_result  = ...
ifft_result = ...
plan_forward  = ...
plan_backward ...

for( i = 0 ; i < SIZE ; i++ ) {
    data[i][0] = array[i];
    data[i][1] = 0.0;
}

Solution

  • There are two problems

    First the statement for creating the array has to errors, the "[]" after the variable and using "{}" instead of "[]" to initialize an array.

    Then from a comment there is an incorrect access of the array items in two ways. The array is one diminutional, not two diminutional. Then the return from the array is an NSNumber and that must be unboxed, that is converted from an NSNumber to a float.

    The following is example code with the errors corrected:

    NSArray * array = @[@0.240128f , @0.240128f , @0.953934f , @1.181351f, @1.382523f, @1.497086f, @1.437790f , @0.851196f];
    float a0 = [array[0] floatValue];
    NSLog(@"a0: %f", a0);
    

    NSLog output:

    a0: 0.240128

    Best bet: take the time to learn about NSArray access and Objective-C in general. There are many resources on the web both as manuals/documentation and tutorials.