奇怪的索引越界异常

时间:2013-03-06 12:48:18

标签: ios objective-c nsmutablearray uiviewanimation

我正在尝试动画删除scrollView中的视图。 scrollView的子视图正在从一个对象数组中填充。每个对象都有一个代表它的视图。有时我删除时会得到一个indexOutOfBounds异常。这是我的删除代码:

-(void)deleteView:(UIView *)viewToDelete{
    [self.myObjects removeObjectAtIndex:viewToDelete.tag];
    [UIView animateWithDuration:0.5 animations:^{
        viewToDelete.alpha = 0.0;
        for (NSInteger index = viewToDelete.tag+1; index<self.myViews.count; index++){
            UIView *view = [self.myViews objectAtIndex:index];
            view.center = CGPointMake(view.center.x,view.center.y-viewToDelete.frame.size.height);
        }
    }]; completion:^(BOOL finished) {
        [view removeFromSuperview];
    }];

    [self.myViews removeObjectAtIndex:viewToDelete.tag];
    for (NSInteger index=0; index<self.myVies.count; index++){
        UIView *view = [self.myViews objectAtIndex:index];
        view.tag = index;
    }

}

2 个答案:

答案 0 :(得分:1)

问题在于动画块

你应该知道动画块是异步处理的,所以在动画过程中可能会调用你最后的代码安静,并在动画块内的迭代循环中弄乱。你应该移动

[self.myViews removeObjectAtIndex:viewToDelete.tag];
for (NSInteger index=0; index<self.myVies.count; index++){
    UIView *view = [self.myViews objectAtIndex:index];
    view.tag = index;
}

到完成块

答案 1 :(得分:0)

此时出现错误[self.myObjects removeObjectAtIndex:viewToDelete.tag];

只要从阵列中删除一个对象,项目总数就会减少。因此,您无法访问该索引处的对象。

你应该真正映射这两个数组self.myObjects和self.myViews。