[英]How to sort an NSArray of known objects such that the FIRST record is ensured to be equal to a known object?
If I have an object and setup such as: 如果我有一个对象和设置,例如:
MyObject *objectOne = ....;
NSArray *arrayOfMyObjects = [self.someObject valueForKey=@"myObjects"] allObjects];
where valueForKey=@"objects" is an NSMutableSet of MyObject types, 其中valueForKey = @“ objects”是MyObject类型的NSMutableSet,
How exactly do I use sorting to ENSURE (or at least attempt to ensure) that objectOne is equal to 我如何精确地使用排序来确保(或至少尝试确保) objectOne等于
[arrayOfMyObjects objectAtIndex:0]
? [arrayOfMyObjects objectAtIndex:0]
?
Basically ensuring that the first object of the NSArray is equal to a known object I have? 基本上确保NSArray的第一个对象等于我拥有的已知对象? This is for the purposes of a UITableView and making sure the top most record is objectOne when it is loaded?
这是出于UITableView的目的,并确保加载时最上面的记录是objectOne ?
I'm guessing there's some sort descriptors trickery required but not quite sure the syntax? 我猜想有些描述符需要技巧,但语法不太确定?
Thanks! 谢谢!
You could use a comparator block to ensure that it is first: 您可以使用比较器块来确保它是第一个:
MyObject *objectOne;
NSArray *array = [[self.someObject valueForKey:@"myObjects"] allObjects];
NSArray *sortedArray = [array sortedArrayUsingComparator:^(id obj1, id obj2) {
if(obj1 == objectOne) return (NSComparisonResult)NSOrderedAscending;
if(obj2 == objectOne) return (NSComparisonResult)NSOrderedDescending;
return (NSComparisonResult)NSOrderedSame;
}];
The typecast on the returns is to remove the compiler warning for incorrect argument types. 返回值上的类型转换是为了消除错误参数类型的编译器警告。
NSOrdered...
are of type enum _NSComparisonResult
, and the method expects a NSComparator, which is defined as NSComparisonResult ^(id obj1, id obj2)
, but NSComparisonResult
and enum _NSComparisonResult
are not the same. NSOrdered...
的类型为enum _NSComparisonResult
,并且该方法需要一个NSComparator,其定义为NSComparisonResult ^(id obj1, id obj2)
,但NSComparisonResult
和enum _NSComparisonResult
不相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.