NSA 배열을 알파벳 순으로 정렬하는 방법은 무엇입니까?
다음으로 채워진 배열을 정렬하려면 어떻게 해야 합니까?[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 배열에 적합하지만 다른 유형의 개체로 확장하고 '이름' 속성에 따라 해당 개체를 정렬하려면 대신 다음 작업을 수행해야 합니다.
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]];
문자열 배열을 정렬하는 또 다른 쉬운 방법은 NSString을 사용하는 것입니다.description다음과 같은 속성:
NSSortDescriptor *valueDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES];
arrayOfSortedStrings = [arrayOfNotSortedStrings sortedArrayUsingDescriptors:@[valueDescriptor]];
알파벳 순서로 정렬하려면 아래 코드를 사용합니다.
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
)
이것은 대부분의 목적에서 이미 좋은 답을 가지고 있지만, 나는 더 구체적인 내 답을 추가할 것입니다.
영어에서, 보통 우리가 알파벳을 쓸 때, 우리는 단어의 첫머리에 있는 "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
'programing' 카테고리의 다른 글
| 판다 파이썬에서 문자열을 날짜 시간 형식으로 변환하는 방법은 무엇입니까? (0) | 2023.05.02 |
|---|---|
| 최신 버전의 OS X(요세미티 또는 엘 캐피탄)를 설치한 후 "pg_tblspc"가 없습니다. (0) | 2023.05.02 |
| Mongoose - ObjectId 배열에 채우기 사용 (0) | 2023.05.02 |
| asyncio.create_task()는 무엇을 합니까? (0) | 2023.05.02 |
| 엑셀이 UTF-8 CSV 파일을 자동으로 인식하도록 강제할 수 있습니까? (0) | 2023.04.27 |