开发者

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];开发者_StackOverflow社区

where valueForKey=@"objects" is an NSMutableSet of MyObject types,

How exactly do I use sorting to ENSURE (or at least attempt to ensure) that objectOne is equal to

[arrayOfMyObjects objectAtIndex:0] ?

Basically ensuring that the first object of the NSArray is equal to a known object I have? This is for the purposes of a UITableView and making sure the top most record is objectOne when it is loaded?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜