Graphics Programs Reference
In-Depth Information
Reordering items
The last bit of functionality you need to replace for BNRItem is the ability to re-order
BNRItem s in the BNRItemStore . Because Core Data will not handle ordering auto-
matically, we must update a BNRItem 's orderingValue every time it is moved in the
table view.
This would get rather complicated if the orderingValue was an integer: every time a
BNRItem was placed in a new index, we would have to change the orderingValue 's
of other BNRItem s. This is why we created orderingValue as a double . We can
take the orderingValue s of the BNRItem that will be before and after the moving
item, add them together, and divide by two. The new orderingValue will fall directly
in between the values of the BNRItem s that surround it. In BNRItemStore.m , modify
moveItemAtIndex:toIndex: to handle reordering items.
- (void)moveItemAtIndex:(int)from
toIndex:(int)to
{
if (from == to) {
return;
}
BNRItem *p = [allItems objectAtIndex:from];
[allItems removeObjectAtIndex:from];
[allItems insertObject:p atIndex:to];
// Computing a new orderValue for the object that was moved
double lowerBound = 0.0;
// Is there an object before it in the array?
if (to > 0) {
lowerBound = [[allItems objectAtIndex:to - 1] orderingValue];
} else {
lowerBound = [[allItems objectAtIndex:1] orderingValue] - 2.0;
}
double upperBound = 0.0;
// Is there an object after it in the array?
if (to < [allItems count] - 1) {
upperBound = [[allItems objectAtIndex:to + 1] orderingValue];
} else {
upperBound = [[allItems objectAtIndex:to - 1] orderingValue] + 2.0;
}
double newOrderValue = (lowerBound + upperBound) / 2.0;
NSLog(@"moving to order %f", newOrderValue);
[p setOrderingValue:newOrderValue];
}
Finally, you can build and run your application. Of course, the behavior is the same as it
always was, but it is now using Core Data.
Search WWH ::




Custom Search