NSArray与NSMutableArray对象存储排序指南
2023.12.19 14:25浏览量:4简介:对NSArray与NSMutableArray按照其存储的对象的属性进行排序
千帆应用开发平台“智能体Pro”全新上线 限时免费体验
面向慢思考场景,支持低代码配置的方式创建“智能体Pro”应用
对NSArray与NSMutableArray按照其存储的对象的属性进行排序
在Objective-C中,NSArray和NSMutableArray是两个非常常用的集合类,它们分别代表了不可变数组和可变数组。当我们需要在这些数组中存储自定义对象时,常常需要按照对象的某个属性进行排序。本文将详细介绍如何对NSArray和NSMutableArray按照其存储的对象的属性进行排序。
一、对NSArray进行排序
由于NSArray是只读的,我们不能直接修改它的内容。但我们可以创建一个新的NSArray,它包含排序后的元素。以下是一个例子,假设我们有一个Person类,它有一个name属性,我们想要按照name属性对一个NSArray进行排序:
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@end
@implementation Person
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSArray *array = @[
[[Person alloc] initWithName:@"John"],
[[Person alloc] initWithName:@"Alice"],
[[Person alloc] initWithName:@"Bob"]
];
// 使用sortedArrayUsingSelector: 方法按照name属性排序
NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
for (Person *person in sortedArray) {
NSLog(@"%@", person.name);
}
}
return 0;
}
二、对NSMutableArray进行排序
对于NSMutableArray,我们可以直接修改它的内容。以下是一个例子,我们仍然使用Person类和name属性,但这次我们使用NSMutableArray:
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@end
@implementation Person
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSMutableArray *array = [NSMutableArray arrayWithObjects:
[[Person alloc] initWithName:@"John"],
[[Person alloc] initWithName:@"Alice"],
[[Person alloc] initWithName:@"Bob"]
];
// 使用sortUsingSelector: 方法按照name属性排序
[array sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
for (Person *person in array) {
NSLog(@"%@", person.name);
}
}
return 0;
}
这两个例子都使用了localizedCaseInsensitiveCompare:选择器,它会忽略大小写进行比较。如果你想要按照其他属性或者以其他方式排序,你需要提供一个比较函数。此外,请注意这两个例子中创建Person对象的代码。这只是为了演示,在实际应用中,你可能会从其他来源获取这些对象。

发表评论
登录后可评论,请前往 登录 或 注册