How do I alphabetically sort a custom object field

2020-06-04 03:29发布

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?

2条回答
你好瞎i
2楼-- · 2020-06-04 04:05

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.

查看更多
唯我独甜
3楼-- · 2020-06-04 04:07
NSSortDescriptor *sortDescriptor =
    [NSSortDescriptor sortDescriptorWithKey:@"name"
                                  ascending:YES
                                   selector:@selector(caseInsensitiveCompare:)];
[nameOfArray sortedArrayUsingDescriptors:@[sortDescriptor]];

Related documentation:

查看更多
登录 后发表回答