天天看點

iphone開發數組排序(數組中包括字典)

1。普通數組排序:

     NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"0",@"8",@"6",@"1",nil];

     NSArray *sortedArray = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){

if ([obj1 intValue] > [obj2 intValue]){

return NSOrderedDescending;

}

if ([obj1 intValue] < [obj2 intValue]){

return NSOrderedAscending;

return NSOrderedSame;

}];

      NSLog(@"排序後的數組:%@",sortedArray);

2.數組中有字典的排序:

    NSMutableArray *myMutableArr = [[[NSMutableArray alloc] init] autorelease];

    NSDictionary *dicOne = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"price",@"2",@"number", nil];

    NSDictionary *dicTWo = [NSDictionary dictionaryWithObjectsAndKeys:@"6",@"price",@"5",@"number", nil];

    NSDictionary *dicThree = [NSDictionary dictionaryWithObjectsAndKeys:@"3",@"price",@"1",@"number", nil];

    NSDictionary *dicFour = [NSDictionary dictionaryWithObjectsAndKeys:@"4",@"price",@"3",@"number", nil];

    [myMutableArr addObject:dicOne];

    [myMutableArr addObject:dicTWo];

    [myMutableArr addObject:dicThree];

    [myMutableArr addObject:dicFour];

    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES]];

    [myMutableArr sortUsingDescriptors:sortDescriptors];

    NSLog(@"排序後的數組%@",myMutableArr);

本文轉自 卓行天下  51CTO部落格,原文連結:http://blog.51cto.com/9951038/1772562,如需轉載請自行聯系原作者

繼續閱讀