objective-c - 如何按字母顺序对 NSMutableArray 中的自定义对象字段进行排序?

标签 objective-c ios nsmutablearray

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

#import <Foundation/Foundation.h>

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

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

@end

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

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 类的商店名称?

最佳答案

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

相关文档:

关于objective-c - 如何按字母顺序对 NSMutableArray 中的自定义对象字段进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8107594/

相关文章:

iphone - "object file format unrecognized, invalid, or unsuitable"Xcode 错误

ios - 限制 iOS 上的文本输入边界

iOS 9 快速操作 (3D Touch)

ios - 具有 CurrentValueSubject 绑定(bind)的 TextField 上的 "Binding<String> action tried to update multiple times per frame"

iphone - 无需注册即可恢复非续订订阅的交易

objective-c - NSMutableArray 只初始化一次

iphone - 每个 View 的单独 UINavigationBars

ios - 无法从我的 for 循环中向 NSmutableArray 添加超过 260 个元素的元素

objective-c - NSMutableArray 返回 NULL

objective-c - 为什么 AudioServicesCreateSystemSoundID 内部抛出异常,却返回 0 作为错误码?