开发者

sort array according to date

Sort array according to date, problem is date saved开发者_如何学Python in string format can this is possible to sort array without change date in NSDate object.(Core Data).

string format is mm/dd/yyyy


You can create the sort with sortDescriptorWithKey:ascending:comparator: and supply a block that will compare any two of your date strings. Available in iOS 4.0 and later.


The way to go here is using the NSArray method -sortedArrayUsingFunction:context:. This works in iOS 2.0 and later and is pretty simple. You would call:

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

And you'll need to define the function like so:

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
}

You'll need your own logic to separate out the year, month, and date of the string so that you can compare each one. I'm not sure if this is less work than converting the strings to dates as Dennis suggested, but you know your program so do the one that works.


    -(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;

}

This works for me.


If the date is stored in a format where an alphabetic sort is equivalent to a date sort, then it can't be done with core data. In that case you have two options:

  1. Add a new NSDate attribute to your database and convert each textual date to a real date and update the record. Then you can sort with core data
  2. Extract all the data into an in-memory array, then sort that with a custom compare method.


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]]];


Sort NSMutableArray as date column,you have any format date this code is work fine.

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


This is my solution.

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];

}

This takes the date, which is currently a string, converts it to a date, then compares it. The sharedDateFormatter is a singleton class for NSDateFormatter, so I wouldn't have to alloc it every time.

I wouldn't use this in a project though, It hangs the main thread, but it may be helpful to someone. If someone knew a better way to do this, that wouldn't block the main thread, id appreciate it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜