如何将CGPoint存储在数组中

6

你好,我正在尝试将移动点存储在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中?
3个回答

18

你应该在最后一行使用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]];
}

2
你应该这样做:
-(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方法中分配/初始化数组,然后仅在此处执行:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *move = [[event allTouches] anyObject];
    CGPoint MovePoint = [move locationInView:self.view];

    [MovePointsArray addObject:[NSValue valueWithCGPoint:MovePoint]];
}

1
如果您想使用arrayWithObjects方法获取一个数组,您还必须将nil作为数组的最后一个元素添加进去。
就像这样:
[MovePointsArray arrayWithObjects:[NSValue valueWithCGPoint:MovePoint], nil];

但是如果要将一个对象添加到现有的数组中,您应该使用addObject方法。

[MovePointsArray addObject:[NSValue valueWithCGPoint:MovePoint]];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接