development

알파벳순으로 NSArray를 정렬하는 방법은 무엇입니까?

big-blog 2020. 2. 26. 07:56
반응형

알파벳순으로 NSArray를 정렬하는 방법은 무엇입니까?


[UIFont familyNames]알파벳 순서로 채워진 배열을 어떻게 정렬 할 수 있습니까?


가장 간단한 방법은 정렬 선택기를 제공하는 것입니다 ( 자세한 내용은 Apple 설명서 ).

목표 -C

sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

빠른

let descriptor: NSSortDescriptor = NSSortDescriptor(key: "YourKey", ascending: true, selector: "localizedCaseInsensitiveCompare:")
let sortedResults: NSArray = temparray.sortedArrayUsingDescriptors([descriptor])

Apple은 알파벳 정렬을위한 여러 선택기를 제공합니다.

  • compare:
  • caseInsensitiveCompare:
  • localizedCompare:
  • localizedCaseInsensitiveCompare:
  • localizedStandardCompare:

빠른

var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
students.sort()
print(students)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

참고


여기에 언급 된 다른 답변 @selector(localizedCaseInsensitiveCompare:)은 NSString 배열에 효과적이지만 다른 유형의 객체로 확장하고 'name'속성에 따라 객체를 정렬하려면 대신이 작업을 수행해야합니다.

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
sortedArray=[anArray sortedArrayUsingDescriptors:@[sort]];

객체는 해당 객체의 이름 속성에 따라 정렬됩니다.

정렬을 대소 문자를 구분하지 않으려면 설명자를 다음과 같이 설정해야합니다.

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

NSNumericSearch와 같은 것을 사용하기 위해 NSString 목록을 정렬하는보다 강력한 방법 :

NSArray *sortedArrayOfString = [arrayOfString sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
        }];

SortDescriptor와 결합하면 다음과 같은 결과가 나타납니다.

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
        return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
    }];
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];

알파벳순으로 정렬하려면 아래 코드를 사용하십시오.

    NSArray *unsortedStrings = @[@"Verdana", @"MS San Serif", @"Times New Roman",@"Chalkduster",@"Impact"];

    NSArray *sortedStrings =
    [unsortedStrings sortedArrayUsingSelector:@selector(compare:)];

    NSLog(@"Unsorted Array : %@",unsortedStrings);        
    NSLog(@"Sorted Array : %@",sortedStrings);

아래는 콘솔 로그입니다.

2015-04-02 16:17:50.614 ToDoList[2133:100512] Unsorted Array : (
    Verdana,
    "MS San Serif",
    "Times New Roman",
    Chalkduster,
    Impact
)

2015-04-02 16:17:50.615 ToDoList[2133:100512] Sorted Array : (
    Chalkduster,
    Impact,
    "MS San Serif",
    "Times New Roman",
    Verdana
)

문자열 배열을 정렬하는 또 다른 쉬운 방법은 다음과 같이 NSString description속성 을 사용하는 것입니다.

NSSortDescriptor *valueDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES];
arrayOfSortedStrings = [arrayOfNotSortedStrings sortedArrayUsingDescriptors:@[valueDescriptor]];

이것은 이미 대부분의 목적에 대한 좋은 대답을 가지고 있지만 더 구체적인 광산을 추가 할 것입니다.

영어에서는 일반적으로 알파벳순으로 문구의 시작 부분에있는 "the"라는 단어를 무시합니다. 따라서 "미국"은 "T"가 아닌 "U"로 주문됩니다.

이것은 당신을 위해 그렇게합니다.

이것들을 카테고리로 분류하는 것이 가장 좋습니다.

// Sort an array of NSStrings alphabetically, ignoring the word "the" at the beginning of a string.

-(NSArray*) sortArrayAlphabeticallyIgnoringThes:(NSArray*) unsortedArray {

    NSArray * sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSString* a, NSString* b) {

        //find the strings that will actually be compared for alphabetical ordering
        NSString* firstStringToCompare = [self stringByRemovingPrecedingThe:a];
        NSString* secondStringToCompare = [self stringByRemovingPrecedingThe:b];

        return [firstStringToCompare compare:secondStringToCompare];
    }];
    return sortedArray;
}

// Remove "the"s, also removes preceding white spaces that are left as a result. Assumes no preceding whitespaces to start with. nb: Trailing white spaces will be deleted too.

-(NSString*) stringByRemovingPrecedingThe:(NSString*) originalString {
    NSString* result;
    if ([[originalString substringToIndex:3].lowercaseString isEqualToString:@"the"]) {
        result = [[originalString substringFromIndex:3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    else {
        result = originalString;
    }
    return result;
}

-(IBAction)SegmentbtnCLK:(id)sender
{ [self sortArryofDictionary];
    [self.objtable reloadData];}
-(void)sortArryofDictionary
{ NSSortDescriptor *sorter;
    switch (sortcontrol.selectedSegmentIndex)
    {case 0:
            sorter=[[NSSortDescriptor alloc]initWithKey:@"Name" ascending:YES];
            break;
        case 1:
            sorter=[[NSSortDescriptor alloc]initWithKey:@"Age" ascending:YES];
            default:
            break; }
    NSArray *sortdiscriptor=[[NSArray alloc]initWithObjects:sorter, nil];
    [arr sortUsingDescriptors:sortdiscriptor];
    }

참고 URL : https://stackoverflow.com/questions/1351182/how-to-sort-a-nsarray-alphabetically



반응형