What I want to do seems pretty simple, but I can't find any answers on the web. I have an NSMutableArray
of objects, and let's say they are 'Person' objects. I want to sort the NSMutableArray
by Person.birthDate which is an NSDate
.
我想做的看起来很简单,但是我在网上找不到任何答案。我有一个NSMutableArray对象,假设它们是“Person”对象。我想用Person来分类NSMutableArray。出生日期是NSDate。
I think it has something to do with this method:
我认为这和这个方法有关
NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(???)];
In Java I would make my object implement Comparable, or use Collections.sort with an inline custom comparator...how on earth do you do this in Objective-C?
在Java中,我将使我的对象实现可比较,或者使用集合。使用内联自定义比较器排序…你在Objective-C中是怎么做的?
26 个解决方案
#1
2210
Compare method
Either you implement a compare-method for your object:
您可以为对象实现一个比较方法:
- (NSComparisonResult)compare:(Person *)otherObject {
return [self.birthDate compare:otherObject.birthDate];
}
NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];
NSSortDescriptor (better)
or usually even better:
或者通常更好:
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES];
NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];
You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at the documentation.
通过向数组中添加多个键,可以轻松地按多个键进行排序。使用自定义比较器方法也是可能的。看一下文档。
Blocks (shiny!)
There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:
也有可能使用block排序,因为Mac OS X 10.6和ios4:
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSDate *first = [(Person*)a birthDate];
NSDate *second = [(Person*)b birthDate];
return [first compare:second];
}];
Performance
The -compare:
and block-based methods will be quite a bit faster, in general, than using NSSortDescriptor
as the latter relies on KVC. The primary advantage of the NSSortDescriptor
method is that it provides a way to define your sort order using data, rather than code, which makes it easy to e.g. set things up so users can sort an NSTableView
by clicking on the header row.
一般来说,基于块的方法比使用NSSortDescriptor (NSSortDescriptor)要快得多,因为后者依赖于KVC。NSSortDescriptor方法的主要优点是它提供了一种使用数据(而不是代码)来定义排序顺序的方法,这使得它很容易设置,这样用户就可以通过单击标题行来排序NSTableView。
#2
103
See the NSMutableArray
method sortUsingFunction:context:
参见NSMutableArray方法sortUsingFunction:上下文:
You will need to set up a compare function which takes two objects (of type Person
, since you are comparing two Person
objects) and a context parameter.
您将需要设置一个比较函数,该函数接受两个对象(类型为Person,因为您正在比较两个Person对象)和一个上下文参数。
The two objects are just instances of Person
. The third object is a string, e.g. @"birthDate".
这两个对象只是人的实例。第三个对象是一个字符串,例如@“birthDate”。
This function returns an NSComparisonResult
: It returns NSOrderedAscending
if PersonA.birthDate
< PersonB.birthDate
. It will return NSOrderedDescending
if PersonA.birthDate
> PersonB.birthDate
. Finally, it will return NSOrderedSame
if PersonA.birthDate
== PersonB.birthDate
.
该函数返回一个nscomparonresult:它返回nsorderedingif角色。生日< PersonB.birthDate。如果是人物角色,它将返回nsordereddescent。生日> PersonB.birthDate。最后,它将返回NSOrderedSame if角色。生日= = PersonB.birthDate。
This is rough pseudocode; you will need to flesh out what it means for one date to be "less", "more" or "equal" to another date (such as comparing seconds-since-epoch etc.):
这是粗略的伪代码;你将需要充实一个日期的含义:“更少”、“更多”或“等于”到另一个日期(例如比较second- sin -epoch等):
NSComparisonResult compare(Person *firstPerson, Person *secondPerson, void *context) {
if ([firstPerson birthDate] < [secondPerson birthDate])
return NSOrderedAscending;
else if ([firstPerson birthDate] > [secondPerson birthDate])
return NSOrderedDescending;
else
return NSOrderedSame;
}
If you want something more compact, you can use ternary operators:
如果你想要更紧凑的东西,你可以使用三元运算符:
NSComparisonResult compare(Person *firstPerson, Person *secondPerson, void *context) {
return ([firstPerson birthDate] < [secondPerson birthDate]) ? NSOrderedAscending : ([firstPerson birthDate] > [secondPerson birthDate]) ? NSOrderedDescending : NSOrderedSame;
}
Inlining could perhaps speed this up a little, if you do this a lot.
如果你经常这样做的话,内联可能会使这个速度加快一点。
#3
58
I did this in iOS 4 using a block. Had to cast the elements of my array from id to my class type. In this case it was a class called Score with a property called points.
我在ios4中使用了一个block。必须将数组的元素从id转换为类类型。在本例中,它是一个名为Score的类,具有一个名为points的属性。
Also you need to decide what to do if the elements of your array are not the right type, for this example I just returned NSOrderedSame
, however in my code I though an exception.
同样,如果数组的元素不是正确的类型,您需要决定要做什么,对于这个示例,我刚刚返回了NSOrderedSame,但是在我的代码I中有一个例外。
NSArray *sorted = [_scores sortedArrayUsingComparator:^(id obj1, id obj2){
if ([obj1 isKindOfClass:[Score class]] && [obj2 isKindOfClass:[Score class]]) {
Score *s1 = obj1;
Score *s2 = obj2;
if (s1.points > s2.points) {
return (NSComparisonResult)NSOrderedAscending;
} else if (s1.points < s2.points) {
return (NSComparisonResult)NSOrderedDescending;
}
}
// TODO: default is the same?
return (NSComparisonResult)NSOrderedSame;
}];
return sorted;
PS: This is sorting in descending order.
这是按降序排序。
#4
28
Starting in iOS 4 you can also use blocks for sorting.
从ios4开始,您还可以使用块进行排序。
For this particular example I'm assuming that the objects in your array have a 'position' method, which returns an NSInteger
.
对于这个特定的例子,我假设数组中的对象有一个“position”方法,它返回一个NSInteger。
NSArray *arrayToSort = where ever you get the array from... ;
NSComparisonResult (^sortBlock)(id, id) = ^(id obj1, id obj2)
{
if ([obj1 position] > [obj2 position])
{
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 position] < [obj2 position])
{
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
};
NSArray *sorted = [arrayToSort sortedArrayUsingComparator:sortBlock];
Note: the "sorted" array will be autoreleased.
注意:“排序”数组将自动发出。
#5
24
I tried all, but this worked for me. In a class I have another class named "crimeScene
", and want to sort by a property of "crimeScene
".
我试了所有的方法,但这对我很有效。在一个类中,我有另一个类名为“crimeScene”,并希望通过“crimeScene”属性进行排序。
This works like a charm:
这就像一个魅力:
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"crimeScene.distance" ascending:YES];
[self.arrAnnotations sortUsingDescriptors:[NSArray arrayWithObject:sorter]];
#6
19
There is a missing step in Georg Schölly's second answer, but it works fine then.
在Georg Scholly的第二个答案中有一个缺失的步骤,但它在那时起作用很好。
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptor:sortDescriptors];
#7
18
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate" ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];
Thanks, it's working fine...
谢谢,工作好…
#8
16
Your Person
objects need to implement a method, say compare:
which takes another Person
object, and return NSComparisonResult
according to the relationship between the 2 objects.
你的Person对象需要实现一个方法,例如compare:它获取另一个Person对象,并根据两个对象之间的关系返回ns比较结果。
Then you would call sortedArrayUsingSelector:
with @selector(compare:)
and it should be done.
然后调用sortedArrayUsingSelector: with @selector(compare:),应该这样做。
There are other ways, but as far as I know there is no Cocoa-equiv of the Comparable
interface. Using sortedArrayUsingSelector:
is probably the most painless way to do it.
还有其他的方法,但是据我所知,没有类似的接口。使用sortedArrayUsingSelector:可能是最简单的方法。
#9
8
iOS 4 blocks will save you :)
iOS 4块将拯救你:)
featuresArray = [[unsortedFeaturesArray sortedArrayUsingComparator: ^(id a, id b)
{
DMSeatFeature *first = ( DMSeatFeature* ) a;
DMSeatFeature *second = ( DMSeatFeature* ) b;
if ( first.quality == second.quality )
return NSOrderedSame;
else
{
if ( eSeatQualityGreen == m_seatQuality || eSeatQualityYellowGreen == m_seatQuality || eSeatQualityDefault == m_seatQuality )
{
if ( first.quality < second.quality )
return NSOrderedAscending;
else
return NSOrderedDescending;
}
else // eSeatQualityRed || eSeatQualityYellow
{
if ( first.quality > second.quality )
return NSOrderedAscending;
else
return NSOrderedDescending;
}
}
}] retain];
http://sokol8.blogspot.com/2011/04/sorting-nsarray-with-blocks.html a bit of description
http://sokol8.blogspot.com/2011/04/sorting-nsarray-with-blocks.html有一点描述。
#10
7
For NSMutableArray
, use the sortUsingSelector
method. It sorts it-place, without creating a new instance.
对于NSMutableArray,使用sortUsingSelector方法。它对它进行排序,而不创建新的实例。
#11
5
If you're just sorting an array of NSNumbers
, you can sort them with 1 call:
如果你只是对nsnumber数组排序,你可以用一个调用来排序:
[arrayToSort sortUsingSelector: @selector(compare:)];
That works because the objects in the array (NSNumber
objects) implement the compare method. You could do the same thing for NSString
objects, or even for an array of custom data objects that implement a compare method.
这是因为数组(NSNumber对象)中的对象实现了compare方法。对于NSString对象,甚至是实现比较方法的自定义数据对象数组,也可以做同样的事情。
Here's some example code using comparator blocks. It sorts an array of dictionaries where each dictionary includes a number in a key "sort_key".
这里有一些示例代码使用比较器模块。这类字典数组,每个字典包含一个数字键“sort_key”。
#define SORT_KEY @\"sort_key\"
[anArray sortUsingComparator:
^(id obj1, id obj2)
{
NSInteger value1 = [[obj1 objectForKey: SORT_KEY] intValue];
NSInteger value2 = [[obj2 objectForKey: SORT_KEY] intValue];
if (value1 > value2)
{
return (NSComparisonResult)NSOrderedDescending;
}
if (value1 < value2)
{
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
The code above goes through the work of getting an integer value for each sort key and comparing them, as an illustration of how to do it. Since NSNumber
objects implement a compare method, it could be rewritten much more simply:
上面的代码通过为每个排序键获取一个整数值的工作,并将它们进行比较,以说明如何操作。因为NSNumber对象实现了一个比较方法,所以可以更简单地重写它:
#define SORT_KEY @\"sort_key\"
[anArray sortUsingComparator:
^(id obj1, id obj2)
{
NSNumber* key1 = [obj1 objectForKey: SORT_KEY];
NSNumber* key2 = [obj2 objectForKey: SORT_KEY];
return [key1 compare: key2];
}];
or the body of the comparator could even be distilled down to 1 line:
或者比较器的主体可以被蒸馏成一行:
return [[obj1 objectForKey: SORT_KEY] compare: [obj2 objectForKey: SORT_KEY]];
I tend to prefer simple statements and lots of temporary variables because the code is easier to read, and easier to debug. The compiler optimizes away the temporary variables anyway, so there is no advantage to the all-in-one-line version.
我倾向于使用简单的语句和大量临时变量,因为代码更容易阅读,也更容易调试。无论如何,编译器都会对临时变量进行优化,因此一行行的版本没有任何优势。
#12
5
You can use the following generic method for your purpose. It should solve your issue.
您可以为您的目的使用以下通用方法。它应该能解决你的问题。
//Called method
-(NSMutableArray*)sortArrayList:(NSMutableArray*)arrDeviceList filterKeyName:(NSString*)sortKeyName ascending:(BOOL)isAscending{
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:sortKeyName ascending:isAscending];
[arrDeviceList sortUsingDescriptors:[NSArray arrayWithObject:sorter]];
return arrDeviceList;
}
//Calling method
[self sortArrayList:arrSomeList filterKeyName:@"anything like date,name etc" ascending:YES];
#13
4
I have created a small library of category methods, called Linq to ObjectiveC, that makes this sort of thing more easy. Using the sort method with a key selector, you can sort by birthDate
as follows:
我创建了一个类别方法的小库,名为Linq to ObjectiveC,它使这类方法更容易。使用带有键选择器的排序方法,您可以按出生日期排序如下:
NSArray* sortedByBirthDate = [input sort:^id(id person) {
return [person birthDate];
}]
#14
4
I just done multi level sorting based on custom requirement.
我刚刚完成了基于自定义需求的多级排序。
//sort the values
/ /排序的值
[arrItem sortUsingComparator:^NSComparisonResult (id a, id b){
ItemDetail * itemA = (ItemDetail*)a;
ItemDetail* itemB =(ItemDetail*)b;
//item price are same
if (itemA.m_price.m_selling== itemB.m_price.m_selling) {
NSComparisonResult result= [itemA.m_itemName compare:itemB.m_itemName];
//if item names are same, then monogramminginfo has to come before the non monograme item
if (result==NSOrderedSame) {
if (itemA.m_monogrammingInfo) {
return NSOrderedAscending;
}else{
return NSOrderedDescending;
}
}
return result;
}
//asscending order
return itemA.m_price.m_selling > itemB.m_price.m_selling;
}];
https://sites.google.com/site/greateindiaclub/mobil-apps/ios/multilevelsortinginiosobjectivec
https://sites.google.com/site/greateindiaclub/mobil-apps/ios/multilevelsortinginiosobjectivec
#15
4
I've used sortUsingFunction:: in some of my projects:
我在一些项目中使用了sortUsingFunction::
int SortPlays(id a, id b, void* context)
{
Play* p1 = a;
Play* p2 = b;
if (p1.score<p2.score)
return NSOrderedDescending;
else if (p1.score>p2.score)
return NSOrderedAscending;
return NSOrderedSame;
}
...
[validPlays sortUsingFunction:SortPlays context:nil];
#16
3
-(NSMutableArray*) sortArray:(NSMutableArray *)toBeSorted
{
NSArray *sortedArray;
sortedArray = [toBeSorted sortedArrayUsingComparator:^NSComparisonResult(id a, id b)
{
return [a compare:b];
}];
return [sortedArray mutableCopy];
}
#17
2
Sorting NSMutableArray
is very simple:
对NSMutableArray进行排序非常简单:
NSMutableArray *arrayToFilter =
[[NSMutableArray arrayWithObjects:@"Photoshop",
@"Flex",
@"AIR",
@"Flash",
@"Acrobat", nil] autorelease];
NSMutableArray *productsToRemove = [[NSMutableArray array] autorelease];
for (NSString *products in arrayToFilter) {
if (fliterText &&
[products rangeOfString:fliterText
options:NSLiteralSearch|NSCaseInsensitiveSearch].length == 0)
[productsToRemove addObject:products];
}
[arrayToFilter removeObjectsInArray:productsToRemove];
#18
1
Sort using NSComparator
这种使用NSComparator
If we want to sort custom objects we need to provide NSComparator
, which is used to compare custom objects. The block returns an NSComparisonResult
value to denote the ordering of the two objects. So in order to sort whole array NSComparator
is used in following way.
如果我们想要对自定义对象进行排序,我们需要提供NSComparator,用于比较定制对象。块返回一个ns比较结果值,以表示两个对象的顺序。为了对整个数组进行排序NSComparator的使用方法如下。
NSArray *sortedArray = [employeesArray sortedArrayUsingComparator:^NSComparisonResult(Employee *e1, Employee *e2){
return [e1.firstname compare:e2.firstname];
}];
Sorts Using NSSortDescriptor
Let’s assume, as an example, that we have an array containing instances of a custom class, Employee has attributes firstname, lastname and age. The following example illustrates how to create an NSSortDescriptor that can be used to sort the array contents in ascending order by the age key.
使用NSSortDescriptor (NSSortDescriptor)排序假设我们有一个包含自定义类实例的数组,Employee有属性firstname, lastname和age。下面的示例演示如何创建一个NSSortDescriptor,它可以用于按年龄键按升序对数组内容进行排序。
NSSortDescriptor *ageDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
NSArray *sortDescriptors = @[ageDescriptor];
NSArray *sortedArray = [employeesArray sortedArrayUsingDescriptors:sortDescriptors];
Sort using Custom Comparisons
Names are strings, and when you sort strings to present to the user you should always use a localized comparison. Often you also want to perform a case insensitive comparison. Here comes an example with (localizedStandardCompare:) to order the array by last and first name.
使用自定义比较名称是字符串,当您对用户进行排序时,您应该始终使用本地化比较。通常还需要执行不区分大小写的比较。这里有一个示例(本地化了的standardcompare:),它按姓氏和名字对数组进行排序。
NSSortDescriptor *lastNameDescriptor = [[NSSortDescriptor alloc]
initWithKey:@"lastName" ascending:YES selector:@selector(localizedStandardCompare:)];
NSSortDescriptor * firstNameDescriptor = [[NSSortDescriptor alloc]
initWithKey:@"firstName" ascending:YES selector:@selector(localizedStandardCompare:)];
NSArray *sortDescriptors = @[lastNameDescriptor, firstNameDescriptor];
NSArray *sortedArray = [employeesArray sortedArrayUsingDescriptors:sortDescriptors];
For reference and detailed discussion please refer: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html
http://www.ios-blog.co.uk/tutorials/objective-c/how-to-sort-nsarray-with-custom-objects/
参考和详细讨论请参考:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html http://www.ios-blog.co.uk/tutorials/objective- c/howto -sort-nsarray-with-custom-objects/
#19
1
Swift's protocols and functional programming makes that very easy you just have to make your class conform to the Comparable protocol, implement the methods required by the protocol and then use the sorted(by: ) high order function to create a sorted array without need to use mutable arrays by the way.
斯威夫特的协议和函数式编程可以非常轻松地,你只需要让你的类符合相应的协议,协议要求的实现方法,然后使用排序(由:)高阶函数创建一个排序数组不需要使用可变数组。
class Person: Comparable {
var birthDate: NSDate?
let name: String
init(name: String) {
self.name = name
}
static func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.birthDate === rhs.birthDate || lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedSame
}
static func <(lhs: Person, rhs: Person) -> Bool {
return lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedAscending
}
static func >(lhs: Person, rhs: Person) -> Bool {
return lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedDescending
}
}
let p1 = Person(name: "Sasha")
p1.birthDate = NSDate()
let p2 = Person(name: "James")
p2.birthDate = NSDate()//he is older by miliseconds
if p1 == p2 {
print("they are the same") //they are not
}
let persons = [p1, p2]
//sort the array based on who is older
let sortedPersons = persons.sorted(by: {$0 > $1})
//print sasha which is p1
print(persons.first?.name)
//print James which is the "older"
print(sortedPersons.first?.name)
#20
0
In my case, I use "sortedArrayUsingComparator" to sort an array. Look at the below code.
在我的例子中,我使用“sortedArrayUsingComparator”对数组进行排序。请看下面的代码。
contactArray = [[NSArray arrayWithArray:[contactSet allObjects]] sortedArrayUsingComparator:^NSComparisonResult(ContactListData *obj1, ContactListData *obj2) {
NSString *obj1Str = [NSString stringWithFormat:@"%@ %@",obj1.contactName,obj1.contactSurname];
NSString *obj2Str = [NSString stringWithFormat:@"%@ %@",obj2.contactName,obj2.contactSurname];
return [obj1Str compare:obj2Str];
}];
Also my object is,
还我的对象,
@interface ContactListData : JsonData
@property(nonatomic,strong) NSString * contactName;
@property(nonatomic,strong) NSString * contactSurname;
@property(nonatomic,strong) NSString * contactPhoneNumber;
@property(nonatomic) BOOL isSelected;
@end
#21
0
Sort Array In Swift
For Swifty
Person below is a very clean technique to achieve above goal for globally. Lets have an example custom class of User
which have some attributes.
中高阶层人下面是一个非常干净的全球技术实现以上目标。允许用户自定义类的一个例子,有一些属性。
class User: NSObject {
var id: String?
var name: String?
var email: String?
var createdDate: Date?
}
Now we have an array which we need to sort on the basis of createdDate
either ascending and/or descending. So lets add a function for date comparison.
现在我们有一个数组,我们需要根据createdDate进行排序,要么提升,要么下降。因此,我们添加一个函数进行日期比较。
class User: NSObject {
var id: String?
var name: String?
var email: String?
var createdDate: Date?
func checkForOrder(_ otherUser: User, _ order: ComparisonResult) -> Bool {
if let myCreatedDate = self.createdDate, let othersCreatedDate = otherUser.createdDate {
//This line will compare both date with the order that has been passed.
return myCreatedDate.compare(othersCreatedDate) == order
}
return false
}
}
Now lets have an extension
of Array
for User
. In simple words lets add some methods only for those Array's which only have User
objects in it.
现在让我们为用户扩展一个数组。简单地说,让我们为那些只包含用户对象的数组添加一些方法。
extension Array where Element: User {
//This method only takes an order type. i.e ComparisonResult.orderedAscending
func sortUserByDate(_ order: ComparisonResult) -> [User] {
let sortedArray = self.sorted { (user1, user2) -> Bool in
return user1.checkForOrder(user2, order)
}
return sortedArray
}
}
Usage for Ascending Order
使用情况升序排序
let sortedArray = someArray.sortUserByDate(.orderedAscending)
Usage for Descending Order
使用情况降序排列
let sortedArray = someArray.sortUserByDate(.orderedAscending)
Usage for Same Order
使用相同的顺序
let sortedArray = someArray.sortUserByDate(.orderedSame)
Above method in
extension
will only be accessible if theArray
is of type[User]
||Array<User>
扩展中的上述方法只有当数组类型为[User] ||数组
时才可访问
#22
0
You have to create sortDescriptor and then you can sort the nsmutablearray by using sortDescriptor like below.
您必须创建sortDescriptor,然后您可以使用sortDescriptor(如下所示)对nsmutablearray进行排序。
let sortDescriptor = NSSortDescriptor(key: "birthDate", ascending: true, selector: #selector(NSString.compare(_:)))
let array = NSMutableArray(array: self.aryExist.sortedArray(using: [sortDescriptor]))
print(array)
#23
0
You use NSSortDescriptor to sort an NSMutableArray with custom objects
使用NSSortDescriptor要对自定义对象的NSMutableArray排序
NSSortDescriptor *sortingDescriptor;
sortingDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES];
NSArray *sortArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];
#24
-1
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"_strPrice"
ascending:sortFlag selector:@selector(localizedStandardCompare:)] ;
#25
-1
You can sort array of custom objects using quick sort. Please find below example using Swift 4
您可以使用快速排序对自定义对象数组进行排序。请参阅下面使用Swift 4的示例
func sortArrayOfPersonInAscendingOrder() {
if self.arrSortingPersons != nil, self.arrSortingPersons.count > 0 {
self.arrSortingPersons.sort(by: { (person1, person2) -> Bool in
return person1.birthDate < person2.birthDate
})
}
print("Sorted Array In Ascending Order:\n\(self.arrSortingPersons)")
}
#26
-3
NSMutableArray *stockHoldingCompanies = [NSMutableArray arrayWithObjects:fortune1stock,fortune2stock,fortune3stock,fortune4stock,fortune5stock,fortune6stock , nil];
NSSortDescriptor *sortOrder = [NSSortDescriptor sortDescriptorWithKey:@"companyName" ascending:NO];
[stockHoldingCompanies sortUsingDescriptors:[NSArray arrayWithObject:sortOrder]];
NSEnumerator *enumerator = [stockHoldingCompanies objectEnumerator];
ForeignStockHolding *stockHoldingCompany;
NSLog(@"Fortune 6 companies sorted by Company Name");
while (stockHoldingCompany = [enumerator nextObject]) {
NSLog(@"===============================");
NSLog(@"CompanyName:%@",stockHoldingCompany.companyName);
NSLog(@"Purchase Share Price:%.2f",stockHoldingCompany.purchaseSharePrice);
NSLog(@"Current Share Price: %.2f",stockHoldingCompany.currentSharePrice);
NSLog(@"Number of Shares: %i",stockHoldingCompany.numberOfShares);
NSLog(@"Cost in Dollars: %.2f",[stockHoldingCompany costInDollars]);
NSLog(@"Value in Dollars : %.2f",[stockHoldingCompany valueInDollars]);
}
NSLog(@"===============================");
#1
2210
Compare method
Either you implement a compare-method for your object:
您可以为对象实现一个比较方法:
- (NSComparisonResult)compare:(Person *)otherObject {
return [self.birthDate compare:otherObject.birthDate];
}
NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];
NSSortDescriptor (better)
or usually even better:
或者通常更好:
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES];
NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];
You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at the documentation.
通过向数组中添加多个键,可以轻松地按多个键进行排序。使用自定义比较器方法也是可能的。看一下文档。
Blocks (shiny!)
There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:
也有可能使用block排序,因为Mac OS X 10.6和ios4:
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSDate *first = [(Person*)a birthDate];
NSDate *second = [(Person*)b birthDate];
return [first compare:second];
}];
Performance
The -compare:
and block-based methods will be quite a bit faster, in general, than using NSSortDescriptor
as the latter relies on KVC. The primary advantage of the NSSortDescriptor
method is that it provides a way to define your sort order using data, rather than code, which makes it easy to e.g. set things up so users can sort an NSTableView
by clicking on the header row.
一般来说,基于块的方法比使用NSSortDescriptor (NSSortDescriptor)要快得多,因为后者依赖于KVC。NSSortDescriptor方法的主要优点是它提供了一种使用数据(而不是代码)来定义排序顺序的方法,这使得它很容易设置,这样用户就可以通过单击标题行来排序NSTableView。
#2
103
See the NSMutableArray
method sortUsingFunction:context:
参见NSMutableArray方法sortUsingFunction:上下文:
You will need to set up a compare function which takes two objects (of type Person
, since you are comparing two Person
objects) and a context parameter.
您将需要设置一个比较函数,该函数接受两个对象(类型为Person,因为您正在比较两个Person对象)和一个上下文参数。
The two objects are just instances of Person
. The third object is a string, e.g. @"birthDate".
这两个对象只是人的实例。第三个对象是一个字符串,例如@“birthDate”。
This function returns an NSComparisonResult
: It returns NSOrderedAscending
if PersonA.birthDate
< PersonB.birthDate
. It will return NSOrderedDescending
if PersonA.birthDate
> PersonB.birthDate
. Finally, it will return NSOrderedSame
if PersonA.birthDate
== PersonB.birthDate
.
该函数返回一个nscomparonresult:它返回nsorderedingif角色。生日< PersonB.birthDate。如果是人物角色,它将返回nsordereddescent。生日> PersonB.birthDate。最后,它将返回NSOrderedSame if角色。生日= = PersonB.birthDate。
This is rough pseudocode; you will need to flesh out what it means for one date to be "less", "more" or "equal" to another date (such as comparing seconds-since-epoch etc.):
这是粗略的伪代码;你将需要充实一个日期的含义:“更少”、“更多”或“等于”到另一个日期(例如比较second- sin -epoch等):
NSComparisonResult compare(Person *firstPerson, Person *secondPerson, void *context) {
if ([firstPerson birthDate] < [secondPerson birthDate])
return NSOrderedAscending;
else if ([firstPerson birthDate] > [secondPerson birthDate])
return NSOrderedDescending;
else
return NSOrderedSame;
}
If you want something more compact, you can use ternary operators:
如果你想要更紧凑的东西,你可以使用三元运算符:
NSComparisonResult compare(Person *firstPerson, Person *secondPerson, void *context) {
return ([firstPerson birthDate] < [secondPerson birthDate]) ? NSOrderedAscending : ([firstPerson birthDate] > [secondPerson birthDate]) ? NSOrderedDescending : NSOrderedSame;
}
Inlining could perhaps speed this up a little, if you do this a lot.
如果你经常这样做的话,内联可能会使这个速度加快一点。
#3
58
I did this in iOS 4 using a block. Had to cast the elements of my array from id to my class type. In this case it was a class called Score with a property called points.
我在ios4中使用了一个block。必须将数组的元素从id转换为类类型。在本例中,它是一个名为Score的类,具有一个名为points的属性。
Also you need to decide what to do if the elements of your array are not the right type, for this example I just returned NSOrderedSame
, however in my code I though an exception.
同样,如果数组的元素不是正确的类型,您需要决定要做什么,对于这个示例,我刚刚返回了NSOrderedSame,但是在我的代码I中有一个例外。
NSArray *sorted = [_scores sortedArrayUsingComparator:^(id obj1, id obj2){
if ([obj1 isKindOfClass:[Score class]] && [obj2 isKindOfClass:[Score class]]) {
Score *s1 = obj1;
Score *s2 = obj2;
if (s1.points > s2.points) {
return (NSComparisonResult)NSOrderedAscending;
} else if (s1.points < s2.points) {
return (NSComparisonResult)NSOrderedDescending;
}
}
// TODO: default is the same?
return (NSComparisonResult)NSOrderedSame;
}];
return sorted;
PS: This is sorting in descending order.
这是按降序排序。
#4
28
Starting in iOS 4 you can also use blocks for sorting.
从ios4开始,您还可以使用块进行排序。
For this particular example I'm assuming that the objects in your array have a 'position' method, which returns an NSInteger
.
对于这个特定的例子,我假设数组中的对象有一个“position”方法,它返回一个NSInteger。
NSArray *arrayToSort = where ever you get the array from... ;
NSComparisonResult (^sortBlock)(id, id) = ^(id obj1, id obj2)
{
if ([obj1 position] > [obj2 position])
{
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 position] < [obj2 position])
{
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
};
NSArray *sorted = [arrayToSort sortedArrayUsingComparator:sortBlock];
Note: the "sorted" array will be autoreleased.
注意:“排序”数组将自动发出。
#5
24
I tried all, but this worked for me. In a class I have another class named "crimeScene
", and want to sort by a property of "crimeScene
".
我试了所有的方法,但这对我很有效。在一个类中,我有另一个类名为“crimeScene”,并希望通过“crimeScene”属性进行排序。
This works like a charm:
这就像一个魅力:
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"crimeScene.distance" ascending:YES];
[self.arrAnnotations sortUsingDescriptors:[NSArray arrayWithObject:sorter]];
#6
19
There is a missing step in Georg Schölly's second answer, but it works fine then.
在Georg Scholly的第二个答案中有一个缺失的步骤,但它在那时起作用很好。
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptor:sortDescriptors];
#7
18
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate" ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];
Thanks, it's working fine...
谢谢,工作好…
#8
16
Your Person
objects need to implement a method, say compare:
which takes another Person
object, and return NSComparisonResult
according to the relationship between the 2 objects.
你的Person对象需要实现一个方法,例如compare:它获取另一个Person对象,并根据两个对象之间的关系返回ns比较结果。
Then you would call sortedArrayUsingSelector:
with @selector(compare:)
and it should be done.
然后调用sortedArrayUsingSelector: with @selector(compare:),应该这样做。
There are other ways, but as far as I know there is no Cocoa-equiv of the Comparable
interface. Using sortedArrayUsingSelector:
is probably the most painless way to do it.
还有其他的方法,但是据我所知,没有类似的接口。使用sortedArrayUsingSelector:可能是最简单的方法。
#9
8
iOS 4 blocks will save you :)
iOS 4块将拯救你:)
featuresArray = [[unsortedFeaturesArray sortedArrayUsingComparator: ^(id a, id b)
{
DMSeatFeature *first = ( DMSeatFeature* ) a;
DMSeatFeature *second = ( DMSeatFeature* ) b;
if ( first.quality == second.quality )
return NSOrderedSame;
else
{
if ( eSeatQualityGreen == m_seatQuality || eSeatQualityYellowGreen == m_seatQuality || eSeatQualityDefault == m_seatQuality )
{
if ( first.quality < second.quality )
return NSOrderedAscending;
else
return NSOrderedDescending;
}
else // eSeatQualityRed || eSeatQualityYellow
{
if ( first.quality > second.quality )
return NSOrderedAscending;
else
return NSOrderedDescending;
}
}
}] retain];
http://sokol8.blogspot.com/2011/04/sorting-nsarray-with-blocks.html a bit of description
http://sokol8.blogspot.com/2011/04/sorting-nsarray-with-blocks.html有一点描述。
#10
7
For NSMutableArray
, use the sortUsingSelector
method. It sorts it-place, without creating a new instance.
对于NSMutableArray,使用sortUsingSelector方法。它对它进行排序,而不创建新的实例。
#11
5
If you're just sorting an array of NSNumbers
, you can sort them with 1 call:
如果你只是对nsnumber数组排序,你可以用一个调用来排序:
[arrayToSort sortUsingSelector: @selector(compare:)];
That works because the objects in the array (NSNumber
objects) implement the compare method. You could do the same thing for NSString
objects, or even for an array of custom data objects that implement a compare method.
这是因为数组(NSNumber对象)中的对象实现了compare方法。对于NSString对象,甚至是实现比较方法的自定义数据对象数组,也可以做同样的事情。
Here's some example code using comparator blocks. It sorts an array of dictionaries where each dictionary includes a number in a key "sort_key".
这里有一些示例代码使用比较器模块。这类字典数组,每个字典包含一个数字键“sort_key”。
#define SORT_KEY @\"sort_key\"
[anArray sortUsingComparator:
^(id obj1, id obj2)
{
NSInteger value1 = [[obj1 objectForKey: SORT_KEY] intValue];
NSInteger value2 = [[obj2 objectForKey: SORT_KEY] intValue];
if (value1 > value2)
{
return (NSComparisonResult)NSOrderedDescending;
}
if (value1 < value2)
{
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
The code above goes through the work of getting an integer value for each sort key and comparing them, as an illustration of how to do it. Since NSNumber
objects implement a compare method, it could be rewritten much more simply:
上面的代码通过为每个排序键获取一个整数值的工作,并将它们进行比较,以说明如何操作。因为NSNumber对象实现了一个比较方法,所以可以更简单地重写它:
#define SORT_KEY @\"sort_key\"
[anArray sortUsingComparator:
^(id obj1, id obj2)
{
NSNumber* key1 = [obj1 objectForKey: SORT_KEY];
NSNumber* key2 = [obj2 objectForKey: SORT_KEY];
return [key1 compare: key2];
}];
or the body of the comparator could even be distilled down to 1 line:
或者比较器的主体可以被蒸馏成一行:
return [[obj1 objectForKey: SORT_KEY] compare: [obj2 objectForKey: SORT_KEY]];
I tend to prefer simple statements and lots of temporary variables because the code is easier to read, and easier to debug. The compiler optimizes away the temporary variables anyway, so there is no advantage to the all-in-one-line version.
我倾向于使用简单的语句和大量临时变量,因为代码更容易阅读,也更容易调试。无论如何,编译器都会对临时变量进行优化,因此一行行的版本没有任何优势。
#12
5
You can use the following generic method for your purpose. It should solve your issue.
您可以为您的目的使用以下通用方法。它应该能解决你的问题。
//Called method
-(NSMutableArray*)sortArrayList:(NSMutableArray*)arrDeviceList filterKeyName:(NSString*)sortKeyName ascending:(BOOL)isAscending{
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:sortKeyName ascending:isAscending];
[arrDeviceList sortUsingDescriptors:[NSArray arrayWithObject:sorter]];
return arrDeviceList;
}
//Calling method
[self sortArrayList:arrSomeList filterKeyName:@"anything like date,name etc" ascending:YES];
#13
4
I have created a small library of category methods, called Linq to ObjectiveC, that makes this sort of thing more easy. Using the sort method with a key selector, you can sort by birthDate
as follows:
我创建了一个类别方法的小库,名为Linq to ObjectiveC,它使这类方法更容易。使用带有键选择器的排序方法,您可以按出生日期排序如下:
NSArray* sortedByBirthDate = [input sort:^id(id person) {
return [person birthDate];
}]
#14
4
I just done multi level sorting based on custom requirement.
我刚刚完成了基于自定义需求的多级排序。
//sort the values
/ /排序的值
[arrItem sortUsingComparator:^NSComparisonResult (id a, id b){
ItemDetail * itemA = (ItemDetail*)a;
ItemDetail* itemB =(ItemDetail*)b;
//item price are same
if (itemA.m_price.m_selling== itemB.m_price.m_selling) {
NSComparisonResult result= [itemA.m_itemName compare:itemB.m_itemName];
//if item names are same, then monogramminginfo has to come before the non monograme item
if (result==NSOrderedSame) {
if (itemA.m_monogrammingInfo) {
return NSOrderedAscending;
}else{
return NSOrderedDescending;
}
}
return result;
}
//asscending order
return itemA.m_price.m_selling > itemB.m_price.m_selling;
}];
https://sites.google.com/site/greateindiaclub/mobil-apps/ios/multilevelsortinginiosobjectivec
https://sites.google.com/site/greateindiaclub/mobil-apps/ios/multilevelsortinginiosobjectivec
#15
4
I've used sortUsingFunction:: in some of my projects:
我在一些项目中使用了sortUsingFunction::
int SortPlays(id a, id b, void* context)
{
Play* p1 = a;
Play* p2 = b;
if (p1.score<p2.score)
return NSOrderedDescending;
else if (p1.score>p2.score)
return NSOrderedAscending;
return NSOrderedSame;
}
...
[validPlays sortUsingFunction:SortPlays context:nil];
#16
3
-(NSMutableArray*) sortArray:(NSMutableArray *)toBeSorted
{
NSArray *sortedArray;
sortedArray = [toBeSorted sortedArrayUsingComparator:^NSComparisonResult(id a, id b)
{
return [a compare:b];
}];
return [sortedArray mutableCopy];
}
#17
2
Sorting NSMutableArray
is very simple:
对NSMutableArray进行排序非常简单:
NSMutableArray *arrayToFilter =
[[NSMutableArray arrayWithObjects:@"Photoshop",
@"Flex",
@"AIR",
@"Flash",
@"Acrobat", nil] autorelease];
NSMutableArray *productsToRemove = [[NSMutableArray array] autorelease];
for (NSString *products in arrayToFilter) {
if (fliterText &&
[products rangeOfString:fliterText
options:NSLiteralSearch|NSCaseInsensitiveSearch].length == 0)
[productsToRemove addObject:products];
}
[arrayToFilter removeObjectsInArray:productsToRemove];
#18
1
Sort using NSComparator
这种使用NSComparator
If we want to sort custom objects we need to provide NSComparator
, which is used to compare custom objects. The block returns an NSComparisonResult
value to denote the ordering of the two objects. So in order to sort whole array NSComparator
is used in following way.
如果我们想要对自定义对象进行排序,我们需要提供NSComparator,用于比较定制对象。块返回一个ns比较结果值,以表示两个对象的顺序。为了对整个数组进行排序NSComparator的使用方法如下。
NSArray *sortedArray = [employeesArray sortedArrayUsingComparator:^NSComparisonResult(Employee *e1, Employee *e2){
return [e1.firstname compare:e2.firstname];
}];
Sorts Using NSSortDescriptor
Let’s assume, as an example, that we have an array containing instances of a custom class, Employee has attributes firstname, lastname and age. The following example illustrates how to create an NSSortDescriptor that can be used to sort the array contents in ascending order by the age key.
使用NSSortDescriptor (NSSortDescriptor)排序假设我们有一个包含自定义类实例的数组,Employee有属性firstname, lastname和age。下面的示例演示如何创建一个NSSortDescriptor,它可以用于按年龄键按升序对数组内容进行排序。
NSSortDescriptor *ageDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
NSArray *sortDescriptors = @[ageDescriptor];
NSArray *sortedArray = [employeesArray sortedArrayUsingDescriptors:sortDescriptors];
Sort using Custom Comparisons
Names are strings, and when you sort strings to present to the user you should always use a localized comparison. Often you also want to perform a case insensitive comparison. Here comes an example with (localizedStandardCompare:) to order the array by last and first name.
使用自定义比较名称是字符串,当您对用户进行排序时,您应该始终使用本地化比较。通常还需要执行不区分大小写的比较。这里有一个示例(本地化了的standardcompare:),它按姓氏和名字对数组进行排序。
NSSortDescriptor *lastNameDescriptor = [[NSSortDescriptor alloc]
initWithKey:@"lastName" ascending:YES selector:@selector(localizedStandardCompare:)];
NSSortDescriptor * firstNameDescriptor = [[NSSortDescriptor alloc]
initWithKey:@"firstName" ascending:YES selector:@selector(localizedStandardCompare:)];
NSArray *sortDescriptors = @[lastNameDescriptor, firstNameDescriptor];
NSArray *sortedArray = [employeesArray sortedArrayUsingDescriptors:sortDescriptors];
For reference and detailed discussion please refer: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html
http://www.ios-blog.co.uk/tutorials/objective-c/how-to-sort-nsarray-with-custom-objects/
参考和详细讨论请参考:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html http://www.ios-blog.co.uk/tutorials/objective- c/howto -sort-nsarray-with-custom-objects/
#19
1
Swift's protocols and functional programming makes that very easy you just have to make your class conform to the Comparable protocol, implement the methods required by the protocol and then use the sorted(by: ) high order function to create a sorted array without need to use mutable arrays by the way.
斯威夫特的协议和函数式编程可以非常轻松地,你只需要让你的类符合相应的协议,协议要求的实现方法,然后使用排序(由:)高阶函数创建一个排序数组不需要使用可变数组。
class Person: Comparable {
var birthDate: NSDate?
let name: String
init(name: String) {
self.name = name
}
static func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.birthDate === rhs.birthDate || lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedSame
}
static func <(lhs: Person, rhs: Person) -> Bool {
return lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedAscending
}
static func >(lhs: Person, rhs: Person) -> Bool {
return lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedDescending
}
}
let p1 = Person(name: "Sasha")
p1.birthDate = NSDate()
let p2 = Person(name: "James")
p2.birthDate = NSDate()//he is older by miliseconds
if p1 == p2 {
print("they are the same") //they are not
}
let persons = [p1, p2]
//sort the array based on who is older
let sortedPersons = persons.sorted(by: {$0 > $1})
//print sasha which is p1
print(persons.first?.name)
//print James which is the "older"
print(sortedPersons.first?.name)
#20
0
In my case, I use "sortedArrayUsingComparator" to sort an array. Look at the below code.
在我的例子中,我使用“sortedArrayUsingComparator”对数组进行排序。请看下面的代码。
contactArray = [[NSArray arrayWithArray:[contactSet allObjects]] sortedArrayUsingComparator:^NSComparisonResult(ContactListData *obj1, ContactListData *obj2) {
NSString *obj1Str = [NSString stringWithFormat:@"%@ %@",obj1.contactName,obj1.contactSurname];
NSString *obj2Str = [NSString stringWithFormat:@"%@ %@",obj2.contactName,obj2.contactSurname];
return [obj1Str compare:obj2Str];
}];
Also my object is,
还我的对象,
@interface ContactListData : JsonData
@property(nonatomic,strong) NSString * contactName;
@property(nonatomic,strong) NSString * contactSurname;
@property(nonatomic,strong) NSString * contactPhoneNumber;
@property(nonatomic) BOOL isSelected;
@end
#21
0
Sort Array In Swift
For Swifty
Person below is a very clean technique to achieve above goal for globally. Lets have an example custom class of User
which have some attributes.
中高阶层人下面是一个非常干净的全球技术实现以上目标。允许用户自定义类的一个例子,有一些属性。
class User: NSObject {
var id: String?
var name: String?
var email: String?
var createdDate: Date?
}
Now we have an array which we need to sort on the basis of createdDate
either ascending and/or descending. So lets add a function for date comparison.
现在我们有一个数组,我们需要根据createdDate进行排序,要么提升,要么下降。因此,我们添加一个函数进行日期比较。
class User: NSObject {
var id: String?
var name: String?
var email: String?
var createdDate: Date?
func checkForOrder(_ otherUser: User, _ order: ComparisonResult) -> Bool {
if let myCreatedDate = self.createdDate, let othersCreatedDate = otherUser.createdDate {
//This line will compare both date with the order that has been passed.
return myCreatedDate.compare(othersCreatedDate) == order
}
return false
}
}
Now lets have an extension
of Array
for User
. In simple words lets add some methods only for those Array's which only have User
objects in it.
现在让我们为用户扩展一个数组。简单地说,让我们为那些只包含用户对象的数组添加一些方法。
extension Array where Element: User {
//This method only takes an order type. i.e ComparisonResult.orderedAscending
func sortUserByDate(_ order: ComparisonResult) -> [User] {
let sortedArray = self.sorted { (user1, user2) -> Bool in
return user1.checkForOrder(user2, order)
}
return sortedArray
}
}
Usage for Ascending Order
使用情况升序排序
let sortedArray = someArray.sortUserByDate(.orderedAscending)
Usage for Descending Order
使用情况降序排列
let sortedArray = someArray.sortUserByDate(.orderedAscending)
Usage for Same Order
使用相同的顺序
let sortedArray = someArray.sortUserByDate(.orderedSame)
Above method in
extension
will only be accessible if theArray
is of type[User]
||Array<User>
扩展中的上述方法只有当数组类型为[User] ||数组
时才可访问
#22
0
You have to create sortDescriptor and then you can sort the nsmutablearray by using sortDescriptor like below.
您必须创建sortDescriptor,然后您可以使用sortDescriptor(如下所示)对nsmutablearray进行排序。
let sortDescriptor = NSSortDescriptor(key: "birthDate", ascending: true, selector: #selector(NSString.compare(_:)))
let array = NSMutableArray(array: self.aryExist.sortedArray(using: [sortDescriptor]))
print(array)
#23
0
You use NSSortDescriptor to sort an NSMutableArray with custom objects
使用NSSortDescriptor要对自定义对象的NSMutableArray排序
NSSortDescriptor *sortingDescriptor;
sortingDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES];
NSArray *sortArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];
#24
-1
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"_strPrice"
ascending:sortFlag selector:@selector(localizedStandardCompare:)] ;
#25
-1
You can sort array of custom objects using quick sort. Please find below example using Swift 4
您可以使用快速排序对自定义对象数组进行排序。请参阅下面使用Swift 4的示例
func sortArrayOfPersonInAscendingOrder() {
if self.arrSortingPersons != nil, self.arrSortingPersons.count > 0 {
self.arrSortingPersons.sort(by: { (person1, person2) -> Bool in
return person1.birthDate < person2.birthDate
})
}
print("Sorted Array In Ascending Order:\n\(self.arrSortingPersons)")
}
#26
-3
NSMutableArray *stockHoldingCompanies = [NSMutableArray arrayWithObjects:fortune1stock,fortune2stock,fortune3stock,fortune4stock,fortune5stock,fortune6stock , nil];
NSSortDescriptor *sortOrder = [NSSortDescriptor sortDescriptorWithKey:@"companyName" ascending:NO];
[stockHoldingCompanies sortUsingDescriptors:[NSArray arrayWithObject:sortOrder]];
NSEnumerator *enumerator = [stockHoldingCompanies objectEnumerator];
ForeignStockHolding *stockHoldingCompany;
NSLog(@"Fortune 6 companies sorted by Company Name");
while (stockHoldingCompany = [enumerator nextObject]) {
NSLog(@"===============================");
NSLog(@"CompanyName:%@",stockHoldingCompany.companyName);
NSLog(@"Purchase Share Price:%.2f",stockHoldingCompany.purchaseSharePrice);
NSLog(@"Current Share Price: %.2f",stockHoldingCompany.currentSharePrice);
NSLog(@"Number of Shares: %i",stockHoldingCompany.numberOfShares);
NSLog(@"Cost in Dollars: %.2f",[stockHoldingCompany costInDollars]);
NSLog(@"Value in Dollars : %.2f",[stockHoldingCompany valueInDollars]);
}
NSLog(@"===============================");