如何按字母顺序对NSMutable数组中的自定义对象字段进行排序? [英] How do I alphabetically sort a custom object field within a NSMutable Array?

查看:122
本文介绍了如何按字母顺序对NSMutable数组中的自定义对象字段进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a custom object like:

#import <Foundation/Foundation.h>

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

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

@end

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

I have an array of NSMutableArray (storeArray) containing Store objects:

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];

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

My question is how can I sort the array by the store name? I know I can sort an array alphabetically by using this line:

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

如何将此应用于Store类的商店名称?

How can I apply this to the store name of my Store class?

推荐答案

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

相关文档:

  • [NSArray sortedArrayUsingDescriptors:]
  • NSSortDescriptor

这篇关于如何按字母顺序对NSMutable数组中的自定义对象字段进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆