Cocoa touch 在NSArray中使用CGPoints

Cocoa touch 在NSArray中使用CGPoints,cocoa-touch,nsarray,cgpoint,Cocoa Touch,Nsarray,Cgpoint,我一直在尝试创建一个数组,在我正在开发的应用程序中声明UIImageView的位置。我想做的是通过使用一个数组,我可以通过x、y和z坐标来存储“玩家”图像的位置。我试图完成的脚本如下所示 NSArray *location[3]; -(IBAction)startup;{ [location addObject: player.center.x]; [location addObject: player.center.y]; [location addObject: playerheight];

我一直在尝试创建一个数组,在我正在开发的应用程序中声明UIImageView的位置。我想做的是通过使用一个数组,我可以通过x、y和z坐标来存储“玩家”图像的位置。我试图完成的脚本如下所示

NSArray *location[3];
-(IBAction)startup;{
[location addObject: player.center.x];
[location addObject: player.center.y];
[location addObject: playerheight];
}

因此,我将能够访问此数组,以“三维”方式在屏幕上移动我的“播放器”,但我不知道如何将CGpoint值转换为NSValues,以便在数组中使用,是否有一种简单的方法在数组内部执行此操作?

要将浮点值转换为对象,请使用NSNumber。NSValue具有用于几何类型(如CGPoint)的包装器。两个都对你有用

[NSValue valueWithCGPoint:player.center];

[NSNumber numberWithFloat:player.center.x];
[NSNumber numberWithFloat:player.center.y];

还要注意的是,
NSArray
没有
addObject
方法(创建NSArray后不能向其添加对象);您需要
NSMutableArray

而不是:

NSArray *location[3];
您可能想要更像:

NSMutableArray *location = [NSMutableArray arrayWithCapacity:3];

对于第一个答案,请添加。 当您需要从阵列中读取
CGPoint
时,您可以使用以下方法:

CGPoint point = [(NSValue *)[pointsArray objectAtIndex:i] CGPointValue];

它一定是一个NSArray吗?为什么不使用结构数组呢

typedef struct {
    CGPoint location;
    CGFloat height;
} PlayerLocation;

PlayerLocation players[3];

players[0].location = player.center;
players[0].height   = playerheight;
或者,根据您的设计,将包含x、y、z坐标的objective-C类声明为IVAR并将这些对象存储到NSArray中可能更有意义

@interface PlayerLocation : NSObject {
  CGPoint location;
  CGFloat height;
}
@end