简体   繁体   English

自定义 Class 对象的排序数组

[英]Sorting Array of Custom Class Objects

I am facing problem that is of sorting.我面临的问题是排序。 The scenario is explained as: i have a class (Suppose of person) and it has suppose 4 attributes (firstName, lastName, Address, salary) i am creating its object and making a collection of all attributes and putting this object in a NSMutableArray and so on.该场景被解释为:我有一个 class(假设是人),它有 4 个属性(名字、姓氏、地址、薪水)很快。 So at every index of array i have one object (ie collection of 4 attributes).因此,在数组的每个索引处,我都有一个 object(即 4 个属性的集合)。 Now i want to sort that array on the basis of salary can anyone help me out regarding this problem, will be thankful.,现在我想根据薪水对该数组进行排序,任何人都可以帮助我解决这个问题,将不胜感激。,

See the documentation for NSArray.请参阅 NSArray 的文档。 It has several sorting methods.它有几种排序方法。 Search for the word "sort" and you'll find 'em.搜索“排序”这个词,你会找到它们。 (You'll want either the block based or function based API). (您需要基于块的 API 或基于 function 的 API)。

use this用这个

NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:@"salary" ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter];
    [yorArrary sortUsingDescriptors:sortDescriptors];

Either you implement a compare-method for your object:您可以为 object 实现比较方法:

- (NSComparisonResult)compare:(Person *)otherObject {
return [self.birthDate compare:otherObject.birthDate];
 }

 NSArray *sortedArray;
 sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];

or usually even better: (The default sorting selector of NSSortDescriptor is compare:)或者通常更好:(NSSortDescriptor 的默认排序选择器是 compare:)

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate"
                                          ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM