How to sort custom object field in NSMutable Array alphabetically?

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 

I have an NSMutableArray (storeArray) array 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 store name? I know that I can sort the array in alphabetical order using this line:

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

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

+7
source share
2 answers
 NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)]; [nameOfArray sortedArrayUsingDescriptors:@[sortDescriptor]]; 

Related Documentation:

+27
source

Regexident's answer is based on NSArrays, the corresponding in-place sorting for NSMutableArray would be -sortUsingDescriptors:

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

Now storeArray it-self will be sorted.

+11
source

All Articles