如何按字母顺序排列NSMutable数组中的自定义对象字段?

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

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

我的问题是我怎样才能按商店名称sorting数组? 我知道我可以使用这一行按字母顺序排列数组:

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

我如何将这个应用到我的Store类的商店名称?

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

相关文档:

  • [NSArray sortedArrayUsingDescriptors:]
  • NSSortDescriptor

Regexident的答案是基于NSArrays,NSMutableArray相应的就地sorting将是-sortUsingDescriptors:

 [storeArray sortUsingDescriptors: [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)]]]; 

现在storeArray它自己将被sorting。