0

Having difficulties apparently with either adding elements to a NSMutableArray or to converting float to a NSNumber.

Here is a working while loop that uses simple C arrays and not NSMutableArray. It was tested with printf's:

    #define MAXSIZE 50

    float xCoordinate [MAXSIZE] = {0.0};
    float yCoordinate [MAXSIZE] = {0.0};

    float x;
    float y;

    // ... some code creating handle from a .txt file

        while ((fscanf(handle, " (%f;%f)", &x, &y)) == 2)
        {
            printf("%f\n",x);
            printf("%f\n",y);

            xCoordinate[n] = x;
            yCoordinate[n] = y;

            printf("Here is value from the array %f\n", xCoordinate[n]);
            printf("Here is value from the array %f\n", yCoordinate[n] );
            n++;
            if ( n >= MAXSIZE)
            {
                break;
            }
        }

The reason I want to switch to the NSMutable array is because I want count number of elements in the xCoordinate or yCoordinate arrays. I think it is easier to just send the function count to an array.

Here are loops that didn't work for me and the don't assign values from scanf to x and y.

Using whileloop:

    NSMutableArray *xCoordinate;
    NSMutableArray *yCoordinate;
    float x;
    float y;
    int n =0;

    while ( ( fscanf(handle, " (%f;%f)", &x, &y) ) == 2)
        {    
            // these 2 lines don't work as suppose to. What's wrong?        
            [xCoordinate addObject:[NSNumber numberWithFloat:x]];
            [yCoordinate addObject:[NSNumber numberWithFloat:y]];


            printf("asdf %f\n", [[xCoordinate objectAtIndex:n] floatValue]);
            printf("asdf %f\n", [[yCoordinate objectAtIndex:n] floatValue]);



            n++;
            if ( n >= MAXSIZE)
            {
                break;
            }
        }

using for loop:

    NSMutableArray *xCoordinate;
    NSMutableArray *yCoordinate;
    float x;
    float y;   

    for  (n=0; ((fscanf(handle, " (%f;%f)", &x, &y)) == 2); n++)
        {
            // these 2 lines don't work as suppose to. What's wrong?        
            [xCoordinate addObject:[NSNumber numberWithFloat:x]];
            [yCoordinate addObject:[NSNumber numberWithFloat:y]];


            printf("asdf %f\n", [[xCoordinate objectAtIndex:n] floatValue]);
            printf("asdf %f\n", [[yCoordinate objectAtIndex:n] floatValue]);

            if ( n >= MAXSIZE)
            {
                break;
            }
        }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Mr_Vlasov
  • 515
  • 2
  • 6
  • 25

1 Answers1

1

You never create the array instances, so you're always trying to add the items to nothing, which is a silent no-op in Objective-C. Change the first lines to:

NSMutableArray *xCoordinate = [NSMutableArray array];
NSMutableArray *yCoordinate = [NSMutableArray array];
Wain
  • 118,658
  • 15
  • 128
  • 151