Objective c 从另一个类调用浮点数组
这里没有问题 如果我有一个带有数组float itemsPosition[20][20]的类A,而我有另一个访问它的类B,我该怎么做 我通常对alloc类A和其他对象的访问执行此操作,但在本例中,我无法在类A中合成浮点数组Objective c 从另一个类调用浮点数组,objective-c,ios,arrays,class,Objective C,Ios,Arrays,Class,这里没有问题 如果我有一个带有数组float itemsPosition[20][20]的类A,而我有另一个访问它的类B,我该怎么做 我通常对alloc类A和其他对象的访问执行此操作,但在本例中,我无法在类A中合成浮点数组 有什么想法吗?浮动是C类型的,因此不能使用典型的Objective C属性直接访问它们 最好的方法是创建一个“accessor”函数,该函数允许类B访问第一个数组项“itemsPosition”的指针。例如“项目位置[0][0]” 在A类的.h文件中: float items
有什么想法吗?浮动是C类型的,因此不能使用典型的Objective C属性直接访问它们 最好的方法是创建一个“accessor”函数,该函数允许类B访问第一个数组项“
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类中,因为您知道这个多维数组的大小是20x20,所以可以很容易地转到下一个数组项的位置:
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);
}
}
}
float*itemsPosition=[classA getItemsPosition];
对于(int-index=0;index<20;index++)
{
//这将带我们到itemPosition[索引]的开头
浮动*ItemsPositionIndex=itemsPosition+(索引*20);
对于(int index2=0;index2<20;index2++)
{
漂浮=*(项目位置指数+指数2);
NSLog(@“浮动%d+%d为%4.2f”,索引,index2,浮动);
}
}
}
让我知道,如果我能为您提供一个示例Xcode项目,对我是否有用 您可以
@synthesis
一个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];
...
}
+我也祝你。。。NSValues也是一种非常优雅、非常客观的C方式来解决这个问题。从来都不知道NSValues!伟大的您只需更改数组声明的最小大小即可<代码>浮点(*ary2)[10]=(浮点(*)[10])[obj.itemsPosition pointerValue]代码>谢谢!我确实尝试过这个,但是我返回了itemsPosition而不是&itemsPosition。我会试试这个!为什么你不能合成?使用setter怎么样?我想是因为float不是一个对象