【问题标题】:calling float array from another class从另一个类调用浮点数组
【发布时间】:2012-10-01 03:49:05
【问题描述】:

这里是菜鸟问题。

如果我有一个带有数组 float itemsPosition[20][20] 的 A 类,而我有另一个 B 类可以访问它,我该怎么做?

我通常这样做是为了分配 A 类并访问其他对象,但在这种情况下,我无法在 A 类中合成浮点数组。

有什么想法吗?

【问题讨论】:

  • 为什么不能合成?使用 setter 怎么样?
  • 我认为是因为 float 不是对象

标签: objective-c ios arrays class


【解决方案1】:

您可以 @synthesizeNSValue 保存指向您的数组的指针。

@interface SomeObject : NSObject
@property (strong, nonatomic) NSValue *itemsPosition;
@end

@implementation SomeObject
@synthesize itemsPosition;
...
static float anArray[20][20];
...
- (void) someMethod
{
    ... add items to the array
    [self setItemsPosition:[NSValue valueWithPointer:anArray]];
}
@end

@implementation SomeOtherObject
...
- (void) someOtherMethod
{
    SomeObject *obj = [[SomeObject alloc] init];
    ...
    float (*ary2)[20] = (float(*)[20])[obj.itemsPosition pointerValue];
    ...
}

【讨论】:

  • +1 也给你... NSValues 也是一种非常优雅、非常客观的 C 方法来解决这个问题。
  • 从来不知道 NSValues!伟大的!会试试这个
  • 您只需更改数组声明的最小大小。 float (*ary2)[10] = (float(*)[10])[obj.itemsPosition pointerValue];
【解决方案2】:

浮点数是 C 类型,因此您不能使用典型的 Objective C 属性来直接访问它们。

最好的办法是创建一个“访问器”函数,让 B 类可以访问第一个数组条目“itemsPosition”的指针。例如。 "itemsPosition[0][0]"

在 A 类的 .h 文件中:

float itemsPosition[20][20];

- (float *) getItemsPosition;

在 .m 文件中:

- (float *) getItemsPosition
{
    // return the location of the first item in the itemsPosition 
    // multidimensional array, a.k.a. itemsPosition[0][0]
    return( &itemsPosition[0][0] );
}

在 B 类中,由于你知道这个多维数组的大小是 20 x 20,你可以很容易地找到下一个数组条目的位置:

    float * itemsPosition = [classA getItemsPosition];
    for(int index = 0; index < 20; index++)
    {
        // this takes us to to the start of itemPosition[index]
        float * itemsPositionAIndex = itemsPosition+(index*20);

        for( int index2 = 0; index2 < 20; index2++)
        {
            float aFloat = *(itemsPositionAIndex+index2);
            NSLog( @"float %d + %d is %4.2f", index, index2, aFloat);
        }
    }
}

让我知道在某个地方为您放置一个示例 Xcode 项目是否对我有用。

【讨论】:

  • 谢谢!我实际上尝试过,但我返回了 itemsPosition 而不是 &itemsPosition。会试试这个!
猜你喜欢
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 2018-07-30
  • 1970-01-01
  • 2012-09-07
  • 2014-02-18
相关资源
最近更新 更多