为什么我的 int 变量在我已经设置后会发生变化?

Why does my int variable change when I've already set it?

我在我的 table 视图上放置了一个 `UIPanGestureRecognizer:

UIPanGestureRecognizer *swipe = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(closeCell:)];
swipe.minimumNumberOfTouches = 1;
swipe.maximumNumberOfTouches = 1;
swipe.delegate = self;
[self.tableView addGestureRecognizer:swipe];

我正在尝试将初始触摸 y 坐标设置为 initialY var。我尝试通过在 swipe.state 等于 UIGestureRecognizerStateBegan 时设置它来做到这一点。这样做的目的是在UIGestureRecognizerStateChanged时使用它,但是在这个方法中,initalY设置为1。这是为什么?

    -(void)closeCell:(UIPanGestureRecognizer *)swipe {

        CGPoint pointInView = [swipe locationInView:swipe.view];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pointInView];
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];


        int initalY;
        int changeInMovement = 0;

        if (indexPath == expandIndexPath) {

            [self.tableView setScrollEnabled:NO];

            if (swipe.state == UIGestureRecognizerStateBegan) {
                CGPoint pointInCell = [swipe locationInView:cell];
                initalY = pointInCell.y;

                NSLog(@"BEGAN");
                NSLog(@"INITIAL Y: %d", initalY);

            }

            if (swipe.state == UIGestureRecognizerStateChanged) {
                CGPoint pointInCell = [swipe locationInView:cell];
                int currentY = pointInCell.y;
                changeInMovement = initalY - currentY;
                NSLog(@"initial Y: %d", initalY);
                NSLog(@"current Y: %d", currentY);
                NSLog(@"change in Y: %d", changeInMovement);

                //THE PROBLEM IS THAT INITAL Y BECOMES 1

            }
        }
}

因为它是一个局部变量。每次调用该方法时都会 "created" 新鲜。

您可以将变量设为静态,这将保留它的值。静态变量在实例之间共享(例如,所有具有相同 class 的视图控制器)和方法调用之间。只需添加关键字 static

static int initalY = 0;
static int changeInMovement = 0;