如何在NSMutable Array中按字母顺序对自定义对象字段进行排序?

7

我有一个自定义对象,例如:

#import <Foundation/Foundation.h>

@interface Store : NSObject{
    NSString *name;
    NSString *address;
}

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *address;

@end

我有一个NSMutableArray数组(storeArray),其中包含Store对象:

store1 = [[Store alloc] init];
store1.name = @"Walmart";    
store1.address = @"walmart address here..";

store2 = [[Store alloc] init];
store2.name = @"Target";
store2.address = @"Target address here..";

store3 = [[Store alloc] init];
store3.name = @"Apple Store";
store3.address = @"Apple store address here..";

//add stores to array
storeArray = [[NSMutableArray alloc] init];
[storeArray addObject:store1];
[storeArray addObject:store2];
[storeArray addObject:store3];

我的问题是如何按店铺名称对数组进行排序?我知道可以使用以下代码按字母顺序对数组进行排序:

[nameOfArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

如何将此应用于我的Store类的商店名称?
2个回答

28
NSSortDescriptor *sortDescriptor =
    [NSSortDescriptor sortDescriptorWithKey:@"name"
                                  ascending:YES
                                   selector:@selector(caseInsensitiveCompare:)];
[nameOfArray sortedArrayUsingDescriptors:@[sortDescriptor]];

相关文档:


10

Regexident的答案是基于NSArray的,对应于NSMutableArray的原地排序方法是-sortUsingDescriptors:

[storeArray sortUsingDescriptors:
                    [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" 
                                                                           ascending:YES 
                                                                            selector:@selector(caseInsensitiveCompare:)]]];
现在,storeArray 本身将被排序。

1
谢谢你。他们有两种方法得到不同的结果,这很奇怪。 - Vivienne Fosh
1
你是什么意思?一个用于原地排序,一个创建新的数组。两个版本都有各自的使用情况。 - vikingosegundo
1
非常感谢...大多数答案都展示了如何对NSArrays进行排序,尽管问题是针对NSMutableArray数组的。这个方法非常有效 :) - Vidhi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接