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

前端 未结 2 761
悲&欢浪女
悲&欢浪女 2021-02-09 10:57

I have a custom object like:

#import 

@interface Store : NSObject{
    NSString *name;
    NSString *address;
}

@property (nonat         


        
相关标签:
2条回答
  • 2021-02-09 11:31
    NSSortDescriptor *sortDescriptor =
        [NSSortDescriptor sortDescriptorWithKey:@"name"
                                      ascending:YES
                                       selector:@selector(caseInsensitiveCompare:)];
    [nameOfArray sortedArrayUsingDescriptors:@[sortDescriptor]];
    

    Related documentation:

    • [NSArray sortedArrayUsingDescriptors:]
    • NSSortDescriptor
    0 讨论(0)
  • 2021-02-09 11:50

    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.

    0 讨论(0)
提交回复
热议问题