Iphone 如何在数组中存储CGPoint
您好,我正在尝试将移动点存储在Iphone 如何在数组中存储CGPoint,iphone,objective-c,xcode,cocoa-touch,Iphone,Objective C,Xcode,Cocoa Touch,您好,我正在尝试将移动点存储在NSMutableArray中,因此我进行了如下尝试 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *move = [[event allTouches] anyObject]; CGPoint MovePoint = [move locationInView:self.view]; if (MovePointsArray==NULL) {
NSMutableArray
中,因此我进行了如下尝试
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *move = [[event allTouches] anyObject];
CGPoint MovePoint = [move locationInView:self.view];
if (MovePointsArray==NULL) {
MovePointsArray=[[NSMutableArray alloc]init];
}
[MovePointsArray arrayWithObjects:[NSValue valueWithCGPoint:MovePoint]];
}
但这不起作用。如何将这些点存储在
NSMutableArray
中?您应该在最后一行中使用addObject:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *move = [[event allTouches] anyObject];
CGPoint MovePoint = [move locationInView:self.view];
if (MovePointsArray==NULL) {
MovePointsArray=[[NSMutableArray alloc]init];
}
[MovePointsArray addObject:[NSValue valueWithCGPoint:MovePoint]];
}
如果要使用方法
arrayWithObjects
获取数组,还必须添加nil
作为数组的最后一个元素
像这样:
[MovePointsArray arrayWithObjects:[NSValue valueWithCGPoint:MovePoint], nil];
但要将对象添加到现有数组中,应使用addObject
方法
[MovePointsArray addObject:[NSValue valueWithCGPoint:MovePoint]];
你应该这样做:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *move = [[event allTouches] anyObject];
CGPoint MovePoint = [move locationInView:self.view];
if (MovePointsArray == NULL) {
MovePointsArray = [[NSMutableArray arrayWithObjects:[NSValue valueWithCGPoint:MovePoint, nil];
}
else {
[MovePointsArray addObject:[NSValue valueWithCGPoint:MovePoint]];
}
}
不要忘记保留/释放阵列,因为您看不到要使用属性访问器
最好是在init方法中alloc/init数组,然后只在此处执行:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *move = [[event allTouches] anyObject];
CGPoint MovePoint = [move locationInView:self.view];
[MovePointsArray addObject:[NSValue valueWithCGPoint:MovePoint]];
}