如何在阵列中存储CGPoint

时间:2011-10-07 14:09:48

标签: 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) {
        MovePointsArray=[[NSMutableArray alloc]init];
    }
    [MovePointsArray arrayWithObjects:[NSValue valueWithCGPoint:MovePoint]];
}

但这不起作用我如何在NSMutableArray

中存储这些点

3 个答案:

答案 0 :(得分:17)

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

答案 1 :(得分: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]];
}

答案 2 :(得分:1)

如果要使用方法arrayWithObjects获取数组,还必须添加nil作为数组的最后一个元素。

像这样:

[MovePointsArray arrayWithObjects:[NSValue valueWithCGPoint:MovePoint], nil];

但是要将对象添加到现有数组,您应该使用addObject方法

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