在NSArray中使用CGPoints

时间:2010-06-04 00:11:28

标签: 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];
}

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

4 个答案:

答案 0 :(得分:11)

要将浮点值转换为对象,请使用NSNumber。 NSValue具有CGPoint等几何类型的包装器。要么适合你。

[NSValue valueWithCGPoint:player.center];

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

答案 1 :(得分:7)

添加第一个答案。 如果您需要从数组中读取CGPoint,则可以使用类似的内容:

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

答案 2 :(得分:0)

另请注意,addObject没有NSArray方法(在创建NSArray后无法将对象添加到NSArray中);你想要NSMutableArray

而不是:

NSArray *location[3];
你可能想要更像的东西:

NSMutableArray *location = [NSMutableArray arrayWithCapacity:3];

答案 3 :(得分:0)

它必须是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类声明为ivars并将这些对象存储到NSArray中可能更有意义。

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