developer tip

NSDictionary 개체의 NSArray를 정렬하는 가장 좋은 방법은 무엇입니까?

optionbox 2020. 11. 6. 08:04
반응형

NSDictionary 개체의 NSArray를 정렬하는 가장 좋은 방법은 무엇입니까?


사전의 배열을 정렬하는 데 어려움을 겪고 있습니다.

내 사전에는 관심, 가격, 인기 등 몇 가지 값이 있습니다.

어떤 제안?


이렇게 사용 NSSortDescriptor하세요 ..

NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES];
stories = [stories sortedArrayUsingDescriptors:@[descriptor]];
recent = [stories copy];

stories정렬하려는 배열입니다. recent정렬 된 사전 값을 가진 또 다른 가변 배열입니다. @"interest"정렬해야하는 키 값 으로을 변경하십시오 .

모두 제일 좋다


[array sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];

나는 그것을 여러 줄로 나누고 싶지 않습니다. 이미 충분히 간단합니다.


부모에서 필요한 자식 속성으로 순회 할 수 있습니다. 예를 들어

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"parent.child.child"  ascending:YES];

Update, sortUsingDescriptors는 이제 sortedArrayUsingDescriptors입니다.

따라서 다음과 같습니다.

items  = [items sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];

두 사전의 관련 필드를 비교하는 정렬 함수를 작성하십시오. 이 버전이 있으면 예를 들어 NSArray#sortedArrayUsingFunction:context:배열을 정렬 하는 사용할 수 있습니다 .

참조 있는 NSArray 클래스 참조


array = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];

배열에 할당하는 것을 잊지 마십시오

참고 URL : https://stackoverflow.com/questions/2393386/best-way-to-sort-an-nsarray-of-nsdictionary-objects

반응형