Simple Code适用于Debug,而不适用于Release

时间:2012-11-06 15:14:18

标签: objective-c nsmutablearray objective-c-category

所以这根本没有意义。我有NSMutableArray的扩展方法将项目从一个索引移动到另一个索引。这是一个相当简单的方法,当我在Debug Configuration中编译我的应用程序时,它可以完美地工作。但是,如果我在发布配置中编译应用程序,如果我从项目向下移动(从索引>到索引),它会崩溃。崩溃不是一个索引越界错误。我的局部变量搞砸了,我不明白为什么。这是整个方法:

- (void)    moveObjectAtIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex{
    if (fromIndex == toIndex) return; 
    if (fromIndex >= self.count) return; 
    if (toIndex >= self.count) toIndex = self.count - 1; //toIndex too large, assume a move to end
    id movingObject = [self objectAtIndex:fromIndex];

    if (fromIndex < toIndex){
        for (int i = fromIndex; i <= toIndex; i++){
            [self replaceObjectAtIndex:i withObject:(i == toIndex) ? movingObject : [self objectAtIndex:i + 1]];
        }
    } else {
        //The problem occurs in this block (though the crash doesn't always occur here)
        id cObject;
        id prevObject;
        for (int i = toIndex; i <= fromIndex; i++){
            //usually on the last loop, my "prevObject" become 'messed up' after the following line:
            cObject = [self objectAtIndex:i];
            [self replaceObjectAtIndex:i withObject:(i == toIndex) ? movingObject : prevObject];
            prevObject = cObject;
        }
    }
}

我无法逐步完成代码,因为它是一个发布版本,但是我已经在循环的每一步中对变量进行了NSLogged。通常,在prevObject完成时,在最后一个循环中为cObject = [self objectAtIndex:i]; var分配一些随机变量。有时它被设置为nil但通常是我的代码中的其他随机变量。如果它nil,当我尝试替换数组中的对象时,代码崩溃了。否则,当我尝试访问数组并收回错误的对象时,它会在以后崩溃。

有没有人知道发生了什么?我的意思是,问题出现在4行代码中,我已经超过了100行。

1 个答案:

答案 0 :(得分:0)

好的,就像问题/崩溃没有任何意义一样,修复也没有任何意义。我已经开始随机更改代码以查看是否有效。将行prevObject = cObject移动到循环的开头就解决了问题。这样做并没有改变逻辑...... Nada ......不应该有所作为。然而,确实如此。谁说编程是合乎逻辑的?这是有效的代码:

- (void)    moveObjectAtIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex{
    if (fromIndex == toIndex) return; 
    if (fromIndex >= self.count) return; 
    if (toIndex >= self.count) toIndex = self.count - 1; //toIndex too large, assume a move to end
    id movingObject = [self objectAtIndex:fromIndex];

    if (fromIndex < toIndex){
        for (int i = fromIndex; i <= toIndex; i++){
            [self replaceObjectAtIndex:i withObject:(i == toIndex) ? movingObject : [self objectAtIndex:i + 1]];
        }
    } else {
        id cObject = nil;
        id prevObject;
        for (int i = toIndex; i <= fromIndex; i++){
            prevObject = cObject;
            cObject = [self objectAtIndex:i];
            [self replaceObjectAtIndex:i withObject:(i == toIndex) ? movingObject : prevObject];
        }
    }
}

那么,是否有人想要了解发生了什么?