IT박스

NSSortDescriptor를 사용하여 배열을 정렬하고 싶습니다.

itboxs 2020. 10. 28. 07:53
반응형

NSSortDescriptor를 사용하여 배열을 정렬하고 싶습니다.


배열 wrt 데이터베이스 정렬과 관련된 문제가 있습니다.

NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"w" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter]; 

[mGlossaryArray sortUsingDescriptors:sortDescriptors]; 
[sorter release];

여기 데이터베이스에는 첫 번째 대문자가 있으며 그 대문자로 인해 적절한 정렬 출력이 표시되지 않습니다. 여기서는 데이터베이스의 테이블 열인 rt "w"로 배열을 정렬하고 있습니다. 여기에 "Cancer"가 "c"보다 먼저 오는 스크린 샷을 첨부했습니다. 그러나 이것은 정확하지 않습니다. 대문자로 된 단어 때문에 알파벳순으로 정렬되지 않습니다.

예. 소문자로 "able"이 있고 "aCid"가 있으면 aCid를 먼저 표시 한 다음 가능합니다. 첫 번째 문자가 대문자이면 "Able"및 "a"와 같이 먼저 오는 경우도 있습니다. 여기 Able이 먼저 표시됩니다.여기에 이미지 설명 입력


여기 살펴보기 : 정렬 설명자 생성 및 사용

대소 문자를 구분하지 않고 비교할 수 있습니다.

NSSortDescriptor *sorter = [[[NSSortDescriptor alloc]
          initWithKey:@"w"
          ascending:YES
          selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter];
[mGlossaryArray sortUsingDescriptors:sortDescriptors]; 

내가 사용한 것처럼 NSSortDescriptor를 사용하면 잘 작동합니다.

   NSSortDescriptor * sortByRank = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];

-localizedStandardCompare : (NSString) 사용을 제안해도 될까요?

"이 방법은 파일 이름이나 기타 문자열이 Finder와 유사한 정렬이 적합한 목록과 테이블에 표시 될 때마다 사용해야합니다.이 방법의 정확한 정렬 동작은 로케일에 따라 다르며 향후 릴리스에서 변경 될 수 있습니다."


소문자 가 포함 된 이름에 따라 배열을 정렬하는 데 사용할 수 있습니다 .

NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:@"w" ascending:YES selector:@selector(caseInsensitiveCompare:)];

NSArray *sortDescriptors = [NSArray arrayWithObject:sorter]; 

[mGlossaryArray sortUsingDescriptors:sortDescriptors];

이 코드는 작은 문자 (예 : rocky, Ajay, john, Bob 등)가있는 알파벳에 따라 이름을 정렬하는 데 잘 작동합니다.


나는 이것이 당신을 위해 트릭을 할 것이라고 생각합니다. 이에 대한 문서는 다음과 같습니다. 문자열 프로그래밍 가이드

Apple이 작성한이 작은 기능을 추가하십시오.

int finderSortWithLocale(id string1, id string2, void *locale)
{
    static NSStringCompareOptions comparisonOptions =
        NSCaseInsensitiveSearch | NSNumericSearch |
        NSWidthInsensitiveSearch | NSForcedOrderingSearch;

    NSRange string1Range = NSMakeRange(0, [string1 length]);

    return [string1 compare:string2
                    options:comparisonOptions
                    range:string1Range
                    locale:(NSLocale *)locale];
}

함수 정의를 헤더에 복사했는지 확인하십시오. 그렇지 않으면 정렬 된 배열에서 컴파일 오류가 발생합니다.

정렬 된 배열의 경우 다음 방법을 사용하십시오.

[mGlossaryArray sortedArrayUsingFunction:finderSortWithLocale context:[NSLocale currentLocale]];

결과는 다음과 같습니다.

  • 선실
  • 카페
  • 중국말
  • 기독교
  • 크리스마스
  • 콜라

이 코드는 저에게 잘 작동합니다.

- (void)sortSearchResultWithInDocumentTypeArray:(NSMutableArray *)aResultArray basedOn:(NSString *)aSearchString {

    NSSortDescriptor * frequencyDescriptor =[[NSSortDescriptor alloc] initWithKey:aSearchString ascending:YES comparator:^(id firstDocumentName, id secondDocumentName) {

        static NSStringCompareOptions comparisonOptions =
        NSCaseInsensitiveSearch | NSNumericSearch |
        NSWidthInsensitiveSearch | NSForcedOrderingSearch;

        return [firstDocumentName compare:secondDocumentName options:comparisonOptions];
     }];

    NSArray * descriptors =    [NSArray arrayWithObjects:frequencyDescriptor, nil];
    [aResultArray sortUsingDescriptors:descriptors];
}

로케일 방법을 사용하는 Apple Finder 정렬의 대체 형식은 비교기 블록을 사용합니다. ARC 환경에 있고 브리징 캐스트 등을 처리하지 않으려는 경우 유용합니다.

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"your_string_key" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
    NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch | NSWidthInsensitiveSearch | NSForcedOrderingSearch;
    NSRange string1Range = NSMakeRange(0, ((NSString *)obj1).length);
    return [(NSString *)obj1 compare: (NSString *)obj2 options: comparisonOptions range: string1Range locale: [NSLocale currentLocale]];
}];

NSArray *sortedArray = [originalArray sortedArrayUsingDescriptors:@[sortDescriptor]];

효율성을 위해 현재 로케일을 지역 변수에 저장하는 것이 좋습니다.

참고 URL : https://stackoverflow.com/questions/5542762/i-want-to-sort-an-array-using-nssortdescriptor

반응형