天天看點

NSSortDescriptor使用注意以及直接排序字元串數組

NSSortDescriptor 指定用于對象數組排序的對象的屬性。

如果是Employee對象需要按照name來排序,就生成下面的descriptor

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:name ascending:YES];

如果需要多個排序,比如先按name排序,再按入職日期排序。那就建立兩個descriptor

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:hireDate ascending:YES];

兩個descriptor放到數組裡一起傳給需要排序的數組。

如果對象就是NSString,就是字元串數組排序,那更簡單了,sortdescriptor的key直接指定為nil,就直接排序對象,而不是對象的某一個屬性了。

    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];

    NSArray *descriptors = [NSArray arrayWithObject:descriptor];

    NSArray *myDataArray = [NSArray arrayWithObjects:@"what", @"xero", @"highligth", @"mountain",@"Victory", @"Balance", nil];

    NSArray *resultArray = [myDataArray sortedArrayUsingDescriptors:descriptors];

    NSLog(@"%@", resultArray);

NSArray 使用sortedArrayUsingDescriptors,傳回排序好的數組。

NSMutableArray可以直接使用sortUsingDescriptors,對數組本身排序。