1

I'm getting started with Objective-C, and there is something about variables scope that I still didn't get. I searched about it, but I still couldn't catch what I'm doing wrong.

I'm trying to create a code that will give me the x,y difference between two point. The first NSLog inside the first IF shows the right value for pointWhereDragBegan.x and .y, but when I try to get the value of the pointWhereDragBegan in the second IF statement, the value I get for pointWhereDragBegan.x is -1.998683 and .y is 0.0.

I'm sure it is something really simple, I just can't catch my mistake.

- (void)drag:(UILongPressGestureRecognizer *)drag{

CGPoint pointWhereDragBegan;
if(drag.state == UIGestureRecognizerStateBegan){
    pointWhereDragBegan = [drag locationInView:self];        
    NSLog(@"Drag started at %f,%f",pointWhereDragBegan.x,pointWhereDragBegan.y);        
}

if(drag.state == UIGestureRecognizerStateEnded){
    CGPoint pointWhereDragEnded = [drag locationInView:self];  

    float xDragged = pointWhereDragEnded.x - pointWhereDragBegan.x;
    float yDragged = pointWhereDragEnded.y - pointWhereDragBegan.y;



    NSLog(@"Drag ended at %f,%f",pointWhereDragEnded.x,pointWhereDragEnded.y);
    NSLog(@"The user moved %f, %f",xDragged,yDragged);
}
}
2
  • You aren't logging pointWhereDragBegan in the second if statement. You're only logging pointWhereDragEnded and the results of the subtractions. Commented Apr 22, 2012 at 21:08
  • I mean't that in the case I logged pointWhereDragBegan in the second if, the values would be -1.998683 and 0. Commented Apr 22, 2012 at 21:13

1 Answer 1

4

drag.state will never be simultaneously UIGestureRecognizerStateBegan and UIGestureRecognizerStateEnded. This method should be invoked twice: once in each state.

As a result, in order to fix your issue, you'll need to persist pointWhereDragBegan outside the method scope. For example, you might use an instance variable.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer, I could make it work creating an instance variable. I was expecting to have an way of doing it without an instance variable. I thought that as I declared the variable outside the IF block, it would reference the same variable anywhere inside the method scope.
But only across one invocation. If the method is called a second time, values assigned in the first invocation are not preserved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.