将对象添加到NSMutableArray或将Float转换为NSNumber

时间:2015-04-28 16:09:35

标签: objective-c nsmutablearray nsnumber

显然很难将元素添加到NSMutableArray或将float转换为NSNumber。

这是一个使用简单C数组而不是NSMutableArray的工作while循环。它已使用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;
            }
        }

我想切换到NSMutable数组的原因是因为我想要xCoordinate或yCoordinate数组中的元素数量。 我认为将函数count发送到数组更容易。

以下是对我不起作用的循环,并且不将scanf中的值赋给x和y。

使用while循环:

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

使用for循环:

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

1 个答案:

答案 0 :(得分:1)

你永远不会创建数组实例,所以你总是试图将这些项添加到空,这是Objective-C中的一个无声的无操作。将第一行更改为:

NSMutableArray *xCoordinate = [NSMutableArray array];
NSMutableArray *yCoordinate = [NSMutableArray array];