2

ここでNoobの質問。

配列 float itemsPosition[20][20] を持つクラス A があり、それにアクセスする別のクラス B がある場合、どうすればよいですか?

クラスAを割り当てて他のオブジェクトにアクセスするために通常行うことですが、この場合、クラスA内でfloat配列を合成できません。

何か案は?

4

2 に答える 2

1

float は C 型であるため、典型的な Objective C のプロパティを使用して直接アクセスすることはできません。

最善の方法は、クラス B が最初の配列エントリ " " のポインタにアクセスできるようにする "アクセサ" 関数を作成することですitemsPosition。EG " 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 プロジェクトをどこかに置いておくと便利かどうか教えてください。

于 2012-10-01T04:42:13.993 に答える
1

配列へのポインタを保持@synthesizeできます。NSValue

@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];
    ...
}
于 2012-10-01T04:43:10.973 に答える