2010-06-04 54 views
4

我一直在嘗試創建一個數組,說明在我一直在努力的應用程序中的UIImageView的位置。我想要做的是通過使用一個數組,我可以通過使用它的x,y和z座標來存儲我的「玩家」圖像的位置。我試圖完成的腳本會是什麼樣子在NSArray中使用CGPoints

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

因此,我將能夠訪問這個數組將我的「玩家」在「3維」屏幕上,但我不知道該怎麼將CGpoint值轉換爲NSValues,以便它們可以在數組中使用,是否有一種簡單的方法可以在數組內部執行此操作?

回答

11

要將浮點值轉換爲對象,請使用NSNumber。 NSValue包含CGPoint等幾何類型的包裝。要麼爲你工作。

[NSValue valueWithCGPoint:player.center]; 

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

另外請注意,有沒有addObject方法NSArray(其被創建後不能對象添加到一個NSArray);你想要NSMutableArray

相反的:

NSArray *location[3]; 

你可能想要更多的東西一樣:

NSMutableArray *location = [NSMutableArray arrayWithCapacity:3]; 
7

要額外增加了第一個答案。 當你需要閱讀CGPoint從陣列背部,你可以使用類似的東西:

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

它有沒有成爲一個NSArray?爲什麼不使用結構數組?

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

PlayerLocation players[3]; 

players[0].location = player.center; 
players[0].height = playerheight; 

,或者根據您的設計可能更有意義的聲明中包含X,Y的Objective-C類,Z座標作爲實例變量和這些對象存儲到一個NSArray。

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