Nik's
Nik's

Reputation: 690

how to store CGPoint in array

Hi I am trying to store the move points in the NSMutableArray so I have tries like this

-(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]];
}

but this doesn't work how can i store these points in NSMutableArray

Upvotes: 6

Views: 4453

Answers (3)

Oliver
Oliver

Reputation: 23500

You should do like this :

-(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]];
    }
}

don't forget to retain / relase the array as you don't see to use a property accessor.

Best, you should alloc/init the array in your init method and then only do here :

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

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

Upvotes: 2

Cyprian
Cyprian

Reputation: 9453

If you want to get an array using method arrayWithObjects you must also add nil as the last element of the array.

like so:

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

but to add an object to an existing array you should use addObject method

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

Upvotes: 1

justadreamer
justadreamer

Reputation: 2440

You should use addObject: in the last line:

-(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]];
}

Upvotes: 18

Related Questions