How to sort NSPredicate

眉间皱痕 提交于 2019-11-30 05:04:38

you have several options how to sort an array:

I'll show a NSSortDescriptor-based approach here.

NSPredicate *predicate = [NSPredicate predicateWithFormat:
                                  @"companyName contains[cd] %@ OR boothNumber beginswith %@",
                                  text,
                                  text];

// commented out old starting point :)
//[results addObjectsFromArray:[all filteredArrayUsingPredicate:predicate]];

// create a descriptor
// this assumes that the results are Key-Value-accessible
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"companyName" 
                                                             ascending:YES];
//
NSArray *results = [[all filteredArrayUsingPredicate:predicate]  
                     sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];

// the results var points to a NSArray object which contents are sorted ascending by companyName key

This should do your job.

The filteredArrayUsingPredicate: function walks through your array and copies all objects that match the predicate into a new array and returns it. It does not provide any sorting whatsoever. It's more of a search.

Use the sorting functions of NSArray, namely sortedArrayUsingComparator:, sortedArrayUsingDescriptors:, sortedArrayUsingFunction:context: and the like, whichever serves you most.

Checkout NSArray Class Reference for details.

BTW: If you want to sort lexically, you may use sortedArrayUsingSelector:@selector(compare:) which will use NSString's compare: function to find the right order.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!