Last active
December 13, 2016 09:36
-
-
Save josephchang10/18b94ecd550fef66d8d474a6aa6c7575 to your computer and use it in GitHub Desktop.
关系型数据库排序字段
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*模型实现*/ | |
double order; | |
if ([self.allItems count]==0) { | |
order = 1.0; | |
} else { | |
order = [[self.privateItems lastObject] orderingValue]+1.0; | |
} | |
NSLog(@"Adding after %d items, order=%.2f",[self.privateItems count], order); | |
/*模型实现*/ | |
/*移动时实现排序*/ | |
Item *item = self.privateItems[fromIndex]; | |
[self.privateItems removeObjectAtIndex:fromIndex]; | |
[self.privateItems insertObject:item atIndex:toIndex]; | |
//为移动的Item对象计算新的orderValue | |
double lowerBound = 0.0; | |
//在数组中,该对象之前是否有其他对象? | |
if(toIndex>0){ | |
lowerBound = [self.privateItems[(toIndex-1)]orderingValue]; | |
}else{ | |
lowerBound = [self.privateItems[1] orderingValue]-2.0; | |
} | |
double upperBound = 0.0; | |
//在数组中,该对象之后是否还有其他对象? | |
if(toIndex<[self.privateItems count]-1){ | |
upperBound = [self.privateItems[(toIndex+1)] orderingValue]; | |
} else { | |
upperBound = [self.privateItems[(toIndex-1)] orderingValue]+2.0; | |
} | |
double newOrderValue = (lowerBound + upperBound)/2.0; | |
NSLog(@"moving to order %f", newOrderValue); | |
item.orderingValue = newOrderValue; | |
} | |
/*移动时实现排序*/ |
如果orderingValue是整数类型,那么实现排序会有点复杂。当某个Item对象移动至新位置时,其他的Item对象的orderingValue属性也要跟着变化。这也是为什么之前将orderingValue的类型声明为double。当orderingValue的类型为double时,只需要找出位于插入位置之前和之后的Item对象,将两个对象的orderingValues属性相加并除以2,就可以得到移动后的新orderingValue。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
实现Item对象的排序功能。因为Core Data在使用关系型数据库保存数据时,默认不会保留行的排列位置,所以当某个Item对象在UITableView对象中的位置发生变化时,就必须更新该对象的orderingValue属性。