developer tip

날짜 문자열 또는 개체의 NSArray 정렬

optionbox 2020. 9. 20. 09:30
반응형

날짜 문자열 또는 개체의 NSArray 정렬


다음 과 같은 NSArray날짜 문자열 (예 : NSString) 을 포함 하는 파일 이 있습니다 . "Thu, 21 May 09 19:10:09 -0700"

NSArray날짜별로 정렬해야 합니다. NSDate먼저 날짜 문자열을 개체 로 변환하는 것에 대해 생각 했지만 NSDate개체 별로 정렬하는 방법에 대해 고민했습니다 .

감사.


날짜를 NSDateNS (Mutable) Array에 객체 로 저장 한 다음 -[NSArray sortedArrayUsingSelector:또는 사용 하고 매개 변수로 -[NSMutableArray sortUsingSelector:]전달 @selector(compare:)합니다. -[NSDate compare:]방법은 날짜를 오름차순으로 정렬합니다. 이것은를 만드는 것보다 간단하고 NSSortDescriptor, 자신 만의 비교 함수를 작성하는 것보다 훨씬 간단합니다. ( NSDate객체는 사용자 정의 코드로 달성하고자하는만큼 효율적으로 서로 자신을 비교하는 방법을 알고 있습니다.)


NSMutableArray"beginDate"유형의 필드 가있는 개체가있는 NSDate경우 다음 NSSortDescriptor과 같이 사용하고 있습니다.

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"beginDate" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];

다음과 같은 것을 사용할 수도 있습니다.

//Sort the array of items by  date
    [self.items sortUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return [obj2.date compare:obj1.date];
    }];

그러나 이것은 날짜가 NSDate오히려 a 로 저장되어 있다고 가정합니다NString . 가급적이면 데이터를 원시 형식으로 저장하는 것이 좋습니다. 이와 같은 상황에서 쉽게 조작 할 수 있습니다.


블록을 사용하여 제자리에서 정렬 할 수 있습니다.

sortedDatesArray = [[unsortedDatesArray sortedArrayUsingComparator: ^(id a, id b) {
    NSDate *d1 = [NSDate dateWithString: s1];
    NSDate *d2 = [NSDate dateWithString: s2];
    return [d1 compare: d2];
}];

날짜 항목보다 더 많이 변환하지 않도록 정렬하기 전에 모든 문자열을 날짜로 변환하는 것이 좋습니다. 모든 정렬 알고리즘은 배열의 항목 수보다 더 많은 문자열을 날짜로 변환합니다 (때로는 훨씬 더 많음).

블록 정렬에 대해 좀 더 알아보기 : http://sokol8.blogspot.com/2011/04/sorting-nsarray-with-blocks.html


제 경우에 효과가 있었던 것은 다음과 같습니다.

    NSArray * aUnsorted = [dataToDb allKeys];
    NSArray * arrKeys = [aUnsorted sortedArrayUsingComparator : ^ NSComparisonResult (id obj1, id obj2) {
        NSDateFormatter * df = [[NSDateFormatter 할당] init];
        [df setDateFormat : @ "dd-MM-yyyy"];
        NSDate * d1 = [df dateFromString : (NSString *) obj1];
        NSDate * d2 = [df dateFromString : (NSString *) obj2];
        return [d1 비교 : d2];
    }];

dd-MM-yyyy 형식의 모든 키가있는 사전이 있습니다. 그리고 allKeys는 정렬되지 않은 사전 키를 반환하며, 데이터를 시간순으로 표시하고 싶었습니다.


사용할 수 있습니다 sortedArrayUsingFunction:context:. 다음은 샘플입니다.

NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {
    NSDate *d1 = [NSDate dateWithString:s1];
    NSDate *d2 = [NSDate dateWithString:s2];
    return [d1 compare:d2];
}

NSArray *sorted = [unsorted sortedArrayUsingFunction:dateSort context:nil];

를 사용하는 NSMutableArray경우 sortArrayUsingFunction:context:대신 사용할 수 있습니다 .


Once you have an NSDate, you can create an NSSortDescriptor with initWithKey:ascending: and then use sortedArrayUsingDescriptors: to do the sorting.


Change this

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"beginDate" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];

To

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Date" ascending:TRUE];
[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];

Just change the KEY: it must be Date always


Swift 3.0

myMutableArray = myMutableArray.sorted(by: { $0.date.compare($1.date) == ComparisonResult.orderedAscending })

참고URL : https://stackoverflow.com/questions/1132806/sort-nsarray-of-date-strings-or-objects

반응형