代码之家  ›  专栏  ›  技术社区  ›  Mark

NSDecimal对象旁边的方括号是什么意思?

  •  1
  • Mark  · 技术社区  · 15 年前

    我正在为我的iPhone应用程序的绘图组件使用coreplot,而且我一直在使用 NSDecimal 经常反对。

    我看到的其中一行代码是这样的:

    -(void)plotPoint:(NSDecimal *)plotPoint forPlotAreaViewPoint:(CGPoint)point
    {
        NSDecimal x;
        //do some calculations on x
        plotPoint[CPCoordinateX] = x;
    }
    

    式中,CpCoordinates定义如下:

    typedef enum _CPCoordinate {
        CPCoordinateX = 0,  ///< X axis
        CPCoordinateY = 1,  ///< Y axis
        CPCoordinateZ = 2   ///< Z axis
    } CPCoordinate;
    

    线路:

    plotPoint[CPCoordinateX] = x;
    

    在我的代码中,我尝试调用此方法,如下所示:

    NSDecimal dec = CPDecimalFromInteger(0);
    [plotSpace plotPoint:&dec forPlotAreaViewPoint:point];
    NSDecimalNumber *newx = [[NSDecimalNumber alloc] initWithDecimal:dec];
    
    NSDecimal x = dec[CPCoordinateX];
    //NSLog(@"converted at: %@", newx);
    

    但我得到编译错误:

    有人能给我解释一下吗?

    2 回复  |  直到 15 年前
        1
  •  4
  •   Georg Fritzsche    15 年前

    plotPoint 是指针,指针可以使用下标运算符像数组一样索引:

    int array[] = { 1, 2, 3 };
    NSLog(@"x=%d, y=%d, z=%d", array[0], array[1], array[2]); 
    // prints "x=1, y=2, z=3"
    int *pointer = array; // implicit conversion to pointer
    NSLog(@"x=%d, y=%d, z=%d", pointer[0], pointer[1], pointer[2]);
    // also prints "x=1, y=2, z=3"
    

    array[0] = 4;
    pointer[1] = 5;
    

    但只能对数组或指针使用下标运算符:

    NSDecimal dec = CPDecimalFromInteger(0);
    dec[0]; // illegal, dec is a single NSDecimal value, not pointer or array
    

    实际通过一个点 -plotPoint:forPlotArrayViewPoint: 您需要一个C样式的数组或一个2或3的动态数组 NSDecimal s(根据方法期望的维度),例如:

    NSDecimal decPoint[] = {
         CPDecimalFromInteger(0),
         CPDecimalFromInteger(0),
         CPDecimalFromInteger(0)
    };
    [plotSpace plotPoint:decPoint forPlotAreaViewPoint:point];
    

    在该数组上,现在还可以使用下标运算符:

    NSDecimal x = decPoint[CPCoordinateX];
    
        2
  •  4
  •   Preet Sangha    15 年前

    推荐文章