MovePossessionAtIndex:From:To


#1

I find it simpler if you move the possession in the allPossessions array after you make the change to the orderingValue in the db.
Maybe it will be of interest to other readers.

- (void)movePossessionAtIndex:(int)from toIndex:(int)to
{
    if(from==to){
        return;
    }
    
    Possession *p = [allPossessions objectAtIndex:from];
    [p retain];
    
    double lowerBound;
    double upperBound;
    
    if (to > 0) {
        // Insert the possession between "to-1" and "to"
        lowerBound = [[[allPossessions objectAtIndex:to - 1] orderingValue] doubleValue];
        upperBound = [[[allPossessions objectAtIndex:to] orderingValue] doubleValue];
        
        [p setOrderingValue:[NSNumber numberWithDouble:(upperBound-lowerBound)/2]];
    } else {
        // Move the 1st possession so that it doesn't occupy the orderValue=0.0 position
        upperBound = [[[allPossessions objectAtIndex:1] orderingValue] doubleValue];
        [[allPossessions objectAtIndex:0] setOrderingValue:[NSNumber numberWithDouble:(upperBound / 2)]];
        
        // Bring p to the 0.0 position
        [p setOrderingValue:[NSNumber numberWithDouble:0.0]];
    }
    
    [allPossessions removeObjectAtIndex:from];
    [allPossessions insertObject:p atIndex:to];
    
    [p release];
}

#2

I find your code easier to understand and simpler.

Can you or anybody explain why the book has the 2 cases for setting the both upperBound and lowerBound? I do not get it first time reading it.
Maybe there is a reason for doing that but I do not see why. Why adding or subtracting 2.0 from the orderingValue?

Thank you.


#3

[quote=“jkmin1”]Can you or anybody explain why the book has the 2 cases for setting the both upperBound and lowerBound? I do not get it first time reading it.
Maybe there is a reason for doing that but I do not see why. Why adding or subtracting 2.0 from the orderingValue?[/quote]

it looks like those other parts of the conditional are to handle the case where the object has been moved to either the start or the end of the list.

it’s a bit convoluted, but 2.0 is added or subtracted so that when divided by 2.0 later in the code we get an orderingValue that is 1.0 less (if the object was moved to the start) or 1.0 greater (if the object was moved to the end) than its neighbor’s orderingValue.