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 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:)];
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]];
Related documentation:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With