繁体   English   中英

根据日期对数组进行排序

[英]sort array according to date

根据日期对数组进行排序,问题是日期以字符串格式保存,这样就可以在不更改日期的情况下对数组进行排序(在NSDate对象中。)(核心数据)。

字符串格式是mm / dd / yyyy

您可以使用sortDescriptorWithKey:ascending:comparator:创建排序,并提供一个将比较您的任何两个日期字符串的块。 在iOS 4.0及更高版本中可用。

此处的方法是使用NSArray方法-sortedArrayUsingFunction:context: 这适用于iOS 2.0及更高版本,非常简单。 您会致电:

sortedArray = [unsortedArray sortedArrayUsingFunction:sortByStringDate context:NULL];

而且您需要像这样定义函数:

NSInteger sortByDateString(id string1, id string2, void *context)
{
    int y1 = [[string1 yearComponent] intValue];
    int y2 = [[string2 yearComponent] intValue];
    if (y1 < y2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        int m1 = [[string1 monthComponent] intValue];
        int m2 = [[string2 monthComponent] intValue];
        if (m1 < m2)
             return NSOrderedAscending;
    // et cetera
}

您将需要自己的逻辑来区分字符串的年,月和日,以便可以比较每个字符串。 我不确定这是否比Dennis所建议的将字符串转换为日期要少,但是您知道您的程序也是如此。

    -(NSMutableArray *)sortByStringDate:(NSMutableArray *)unsortedArray
{
    NSMutableArray *tempArray=[NSMutableArray array];
    for(int i=0;i<[unsortedArray count];i++)
    {

        NSDateFormatter *df=[[NSDateFormatter alloc]init];
      objModel=[unsortedArray objectAtIndex:i];

        [df setDateFormat:@"MM/dd/yyyy"];
        NSDate *date=[df dateFromString:objModel.sDate];
        NSMutableDictionary *dict=[NSMutableDictionary dictionary];
        [dict setObject:objModel forKey:@"entity"];
        [dict setObject:date forKey:@"date"];
        [tempArray addObject:dict];
    }

    NSInteger counter=[tempArray count];
    NSDate *compareDate;
    NSInteger index;
    for(int i=0;i<counter;i++)
    {
        index=i;
        compareDate=[[tempArray objectAtIndex:i] valueForKey:@"date"];
        NSDate *compareDateSecond;
        for(int j=i+1;j<counter;j++)
        {
            compareDateSecond=[[tempArray objectAtIndex:j] valueForKey:@"date"];
            NSComparisonResult result = [compareDate compare:compareDateSecond];
           if(result == NSOrderedAscending)
           {
               compareDate=compareDateSecond;
               index=j;
           }
        }
        if(i!=index)
          [tempArray exchangeObjectAtIndex:i withObjectAtIndex:index];
    }


    [unsortedArray removeAllObjects];
    for(int i=0;i<[tempArray count];i++)
    {
        [unshortedArray addObject:[[tempArray objectAtIndex:i] valueForKey:@"entity"]];
    }
    return unsortedArray;

}

这对我有用。

将NSMutableArray排序为日期列,您可以使用任何格式的日期,此代码都可以正常工作。

 NSSortDescriptor *sorter =[[NSSortDescriptor alloc] initWithKey:@"Date column name" ascending:sortCheck selector:@selector(compare:)];
                    [itemsData sortUsingDescriptors:[NSArray arrayWithObject:sorter]];

这是我的解决方案。

NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {

[[DateFormatter sharedDateFormatter]setDateStyle:NSDateFormatterShortStyle];
NSDate *d1 = [[DateFormatter sharedDateFormatter] dateFromString:s1];
NSDate *d2 = [[DateFormatter sharedDateFormatter] dateFromString:s2];
return [d1 compare:d2];

}

该日期采用当前为字符串的日期,将其转换为日期,然后进行比较。 sharedDateFormatter是NSDateFormatter的单例类,因此我不必每次都分配它。

我不会在项目中使用它,它会挂起主线程,但对某人可能会有帮助。 如果有人知道更好的方法,那不会阻塞主线程,请欣赏它。

如果日期以字母排序等同于日期排序的格式存储,则不能使用核心数据来完成。 在这种情况下,您有两种选择:

  1. 向您的数据库添加一个新的NSDate属性,并将每个文本日期转换为实际日期并更新记录。 然后,您可以对核心数据进行排序
  2. 将所有数据提取到内存数组中,然后使用自定义的compare方法对其进行排序。
NSMutableArray* scores;


scores = [NSMutableArray arrayWithArray:[defaults
objectForKey:@"HighScores"]];
[scores addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"Andrew", @"Name", [NSNumber numberWithUnsignedInt:45], @"Score", nil]];
[scores addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"Andrew2", @"Name", [NSNumber numberWithUnsignedInt:55], @"Score", nil]];
[scores sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"Score" ascending:NO] autorelease]]];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM