0

在我的应用程序中,我有这个代码来拖动一个对象

我摆好姿势:

UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer new] initWithTarget:self action:@selector(dragGestureChanged:)];
downwardGesture.minimumPressDuration = 0.2;
[grid_element addGestureRecognizer:downwardGesture];
for (UILongPressGestureRecognizer *gestureRecognizer in self.view.gestureRecognizers)
{
    [gestureRecognizer requireGestureRecognizerToFail:downwardGesture];
}

在我的方法中:

- (void) dragGestureChanged:(UILongPressGestureRecognizer*)gesture{

    UIImageView *imageToMove;
    CGPoint pointInSelfView;

    if (gesture.state == UIGestureRecognizerStateBegan)
    {
        dragging = TRUE;
        CGPoint location = [gesture locationInView:grid_element];
        NSIndexPath *selectedIndexPath = [grid_element indexPathForItemAtPoint:location];
        if (selectedIndexPath==nil) {
            dragging = FALSE;
            return;
        }

        indexToHide = selectedIndexPath.row;
        imageToMove = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"image_1.png"]];
        [self.view addSubview:imageToMove];
        pointInSelfView = [gesture locationInView:self.view];
        [imageToMove setCenter:pointInSelfView];


    }
    else if (gesture.state == UIGestureRecognizerStateChanged)
    {
        pointInSelfView = [gesture locationInView:self.view];
        [imageToMove setCenter:pointInSelfView];

    }
    else if (gesture.state == UIGestureRecognizerStateEnded     ||
             gesture.state == UIGestureRecognizerStateCancelled ||
             gesture.state == UIGestureRecognizerStateFailed)
    {
        dragging = FALSE;
    }
}

它起作用UIGestureRecognizerStateBegan,然后imageToMove添加self.view到正确的位置,但imageToMove不要拖入UIGestureRecognizerStateChanged;我显示了一个NSLogfor pointInSelfViewinUIGestureRecognizerStateChanged并且它正确地改变了;问题出在哪里?

编辑

如果我使用 imageToMove 作为 IBOutlet 它工作正常,但我不明白其中的区别。

4

1 回答 1

0

如果你使用 ARC,iOS 系统正在释放 object- imageToMove
创建具有保留属性的属性,使系统保留对象并因此移动。

我唯一感到困惑的是为什么[imageToMove setCenter:pointInSelfView];. 应该有一个错误说 -消息被发送到解除分配的实例。但我很确定问题是由于 imageToMove 的内存释放造成的。

于 2013-10-16T09:09:12.773 回答