How to sort NSArray of objects based on one attribute

前端 未结 2 1288
忘了有多久
忘了有多久 2020-12-03 07:00

I am trying to sort an array of managed objects alphabetically. The attribue that they need to be sorted by is the name of the object (NSString) with is one of the managed a

相关标签:
2条回答
  • 2020-12-03 07:14

    You can do this by using NSSortDescriptor,

    eg.

    `NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc]initWithKey:@"distance" ascending:YES];`
    

    // Here I am sorting on behalf of distance. You should write your own key.

    NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor];
    NSArray *sortedArray=[yourArray sortedArrayUsingDescriptors:descriptors];`
    
    0 讨论(0)
  • 2020-12-03 07:18

    Use NSSortDescriptor. Just search the documentation on it and there some very simple examples you can copy right over. Here is a simplified example:

    NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"MyStringVariableName" ascending:YES];
    NSArray *descriptors = [NSArray arrayWithObject:valueDescriptor]; 
    NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:descriptors]; 
    

    And just like that you have a sorted array.

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