处理对象集合:数组排序与查询
立即解锁
发布时间: 2025-08-21 01:59:20 阅读量: 2 订阅数: 9 

### 处理对象集合:数组排序与查询
在开发过程中,我们经常需要处理对象集合,其中数组是一种常见的数据结构。本篇博客将深入探讨如何对数组进行排序以及如何根据特定条件查询数组中的元素。
#### 1. 数组排序
在实际开发中,我们可能会使用数组来分组自定义对象,并希望这些对象能按照其属性值进行排序展示。
##### 1.1 解决方案
要实现数组排序,我们需要为每个用于排序的属性创建一个 `NSSortDescriptor` 对象,然后将这些对象放入一个数组中,最后使用 `NSArray` 的 `sortedArrayUsingDescriptors:` 方法,并将包含 `NSSortDescriptor` 对象的数组作为参数传入,从而返回一个按指定属性排序的数组。
##### 1.2 示例代码
以下是一个使用 `Person` 对象进行排序的示例:
```objc
// Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property(strong) NSString *firstName;
@property(strong) NSString *lastName;
@property(assign) int age;
-(id)initWithFirstName:(NSString *)fName lastName:(NSString *)lName andAge:(int)a;
-(void)reportState;
@end
// Person.m
#import "Person.h"
@implementation Person
@synthesize firstName, lastName, age;
-(id)initWithFirstName:(NSString *)fName lastName:(NSString *)lName andAge:(int)a {
self = [super init];
if (self) {
self.firstName = fName;
self.lastName = lName;
self.age = a;
}
return self;
}
-(void)reportState {
NSLog(@"This person's name is %@ %@ who is %i years old", firstName, lastName, age);
}
@end
// main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main (int argc, const char * argv[]) {
@autoreleasepool {
// 实例化 Person 对象并添加到数组中
Person *p1 = [[Person alloc] initWithFirstName:@"Rebecca" lastName:@"Smith" andAge:33];
Person *p2 = [[Person alloc] initWithFirstName:@"Albert" lastName:@"Case" andAge:24];
Person *p3 = [[Person alloc] initWithFirstName:@"Anton" lastName:@"Belfey" andAge:45];
Person *p4 = [[Person alloc] initWithFirstName:@"Tom" lastName:@"Gun" andAge:17];
Person *p5 = [[Person alloc] initWithFirstName:@"Cindy" lastName:@"Lou" andAge:6];
Person *p6 = [[Person alloc] initWithFirstName:@"Yanno" lastName:@"Dirst" andAge:76];
NSArray *listOfObjects = [NSArray arrayWithObjects:p1, p2, p3, p4, p5, p6, nil];
NSLog(@"PRINT OUT ARRAY UNSORTED");
[listOfObjects makeObjectsPerformSelector:@selector(reportState)];
// 创建三个排序描述符并添加到
```
0
0
复制全文
相关推荐










