NSSortDescriptor

本文介绍了如何使用NSSortDescriptor对包含自定义类实例的NSArray进行排序。通过多个示例展示了按年龄、入职日期及姓名等属性进行排序的方法,并解释了如何实现自定义比较逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Specifying Sorts Using NSSortDescriptor

 

 

Let’s assume, as an example, that we have an array (an instance of NSArray) containing instances of a custom class, Employee (that meets the requirements set out in “Requirements of Collection Objects”). The Employee class has attributes for an employee’s first and last name (instances of NSString), date of hire (an instance of NSDate), and age (an instance of NSNumber).

 

 

1:Sorting the array by the age key

ageDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"age"
                                           ascending:YES] autorelease];
sortDescriptors = [NSArray arrayWithObject:ageDescriptor];
sortedArray = [employeesArray sortedArrayUsingDescriptors:sortDescriptors];

 

2:Sorting the array by the age and date of hire key

ageDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"age"
                                                    ascending:YES] autorelease];
hireDateDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"hireDate"
                                                     ascending:YES] autorelease];
sortDescriptors = [NSArray arrayWithObjects:ageDescriptor, hireDateDescriptor, nil];
sortedArray = [employeesArray sortedArrayUsingDescriptors:sortDescriptors];

 

 

Specifying Custom Comparisons

 

 

 Sorting the array using a localized case insensitive comparison

 

lastNameDescriptor = [[[NSSortDescriptor alloc]
              initWithKey:@"lastName"
              ascending:YES
              selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
 firstNameDescriptor = [[[NSSortDescriptor alloc]
              initWithKey:@"firstName"
              ascending:YES
              selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
 sortDescriptors = [NSArray arrayWithObjects:lastNameDescriptor,
              firstNameDescriptor, nil];
 sortedArray = [peopleArray sortedArrayUsingDescriptors:sortDescriptors];

 
The Foundation classes that have methods that can be used with sort descriptors are listed in Table 1.

 

Table 1  Common Foundation classes and comparison methods

 

 

 写道
Comparison Method Supporting Classes

compare: NSString, NSMutableString, NSDate, NSCalendarDate, NSValue (scalar types and unsigned char only), NSNumber
caseInsensitiveCompare: NSString, NSMutableString
localizedCompare: NSString, NSMutableString
localizedCaseInsensitiveCompare: NSString, NSMutableString
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值