Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I alphabetically sort a custom object field within a NSMutable Array?

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?

like image 749
Andrew Davis Avatar asked Nov 12 '11 21:11

Andrew Davis


2 Answers

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

Related documentation:

  • [NSArray sortedArrayUsingDescriptors:]
  • NSSortDescriptor
like image 186
Regexident Avatar answered Nov 10 '22 02:11

Regexident


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.

like image 28
vikingosegundo Avatar answered Nov 10 '22 03:11

vikingosegundo