使用日期字符串排序数组而不使用比较

时间:2014-09-30 06:55:11

标签: ios6

大家 我又乱了。我需要对数组中的日期进行排序,字符串和名称对应于他们的生日(日期)。然后在表视图中查看它。有什么办法吗?

2 个答案:

答案 0 :(得分:0)

使用此功能按生日排序。并根据您的要求制定条件。

-(void)sortAllDate:(NSMutableArray *)arrayToSort
    {
        NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self"
                                                                   ascending:YES];
        NSArray *descriptors = [NSArray arrayWithObject:descriptor];
        NSArray *reverseOrder = [arrayToSort sortedArrayUsingDescriptors:descriptors];

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"MM-dd-yyyy"];

        NSMutableArray *temp = [[NSMutableArray alloc] init];

        for (int k=0; k<[reverseOrder count]; k++) {

            for(int m=0;m<[frdArray count];m++)
            {
                NSString *dateStr = [NSString stringWithFormat:@"%@",[[frdArray objectAtIndex:m] birthday]];
                if([dateStr isEqualToString:[formatter stringFromDate:[reverseOrder objectAtIndex:k]]])
                {

                    [temp addObject:[frdArray objectAtIndex:m]];
                }
            }
        }

        frdArray = temp;

    }

答案 1 :(得分:-1)

NSDateFormatter * formatter = [[NSDateFormatter alloc] init];     [formatter setDateFormat:@&#34; MM / dd&#34;];

sortedDataSource = [BdayArr sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
    NSDate *d1 = [formatter dateFromString:obj1[kKeyDOB]];
    NSDate *d2 = [formatter dateFromString:obj2[kKeyDOB]];

    return [d1 compare:d2]; // ascending order
    //return [d2 compare:d1]; // descending order
}];

NSLog(@"%@",sortedDataSource);
}