How can I sort an NSMutableArray alphabetically?

后端 未结 6 538
迷失自我
迷失自我 2020-12-08 05:17

I want to sort an NSMutableArray alphabetically.

相关标签:
6条回答
  • 2020-12-08 05:23

    You can do this to sort NSMutableArray:

    [yourArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    
    0 讨论(0)
  • 2020-12-08 05:33

    The other answers provided here mention using @selector(localizedCaseInsensitiveCompare:)
    This works great for an array of NSString, however the OP commented that the array contains objects and that sorting should be done according to object.name property.
    In this case you should do this:

    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    [yourArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
    

    Your objects will be sorted according to the name property of those objects.

    0 讨论(0)
  • 2020-12-08 05:34

    Use the NSSortDescriptor class and rest you will get every thing here

    0 讨论(0)
  • 2020-12-08 05:36
    NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; // Describe the Key value using which you want to sort. 
    NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor]; // Add the value of the descriptor to array.
    sortedArrayWithName = [yourDataArray sortedArrayUsingDescriptors:descriptors]; // Now Sort the Array using descriptor.
    

    Here you will get the sorted array list.

    0 讨论(0)
  • 2020-12-08 05:39

    Maybe this can help you:

    [myNSMutableArray sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES],[NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES]]];
    

    All is acording to NSSortDescriptor...

    0 讨论(0)
  • 2020-12-08 05:45
    NSSortDescriptor * sortDescriptor;
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Name_your_key_value" ascending:YES];
    NSArray * sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 
    NSArray * sortedArray;
    sortedArray = [Your_array sortedArrayUsingDescriptors:sortDescriptors];
    
    0 讨论(0)
提交回复
热议问题