So this isn’t making sense at all. I have an extension method to NSMutableArray to move an item from one index to another. It’s a fairly simple method and it works flawlessly when I compile my app in Debug Configuration. However, if I compile the app in Release Configuration, it crashes if I move from an item down (from index > to index). The crash isn’t a an index out of bounds error. My local variable are being messed up and I have no idea why. Here’s the entire method:
- (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;
}
}
}
I can’t step through the code since it’s a release build, but I’ve NSLogged the variables at each step through the loop. Usually, on the last loop the prevObject var is assigned some random variable when cObject = [self objectAtIndex:i]; completes. Sometimes it’s set to nil but often it’s some other random variable in my code. If it’s nil the code crashes when I try to replace the object in the array. Otherwise, it crashes later on when I try to access the array and receive back the wrong object.
Does anyone have any idea what’s going on? I mean, the problem is occurring in 4 lines of code, which I’ve been over a hundred times.
Ok, just as the problem/crash made no sense, so also the fix doesn’t make any sense at all. I had started to just randomly change up the code to see if anything would work. Moving the line:
prevObject = cObjectto the very beginning of the loop fixed the problem. Doing this didn’t change the logic at all… Nada… shouldn’t have made a difference. And yet, it did. Whoever said programming is logical? Here’s the code that works:So, anybody want to chime in as to what’s going on?