2016-09-27 1 views
0

내가 정렬되지 않은 NSMutableDictioanry이이 dictioanry 예를정렬 변경 가능한 사전은 그것의 값

{ 
    1 = 27; 
    2 = 5; 
    3 = 13964; 
    4 = 2422; 
    5 = 45; 
    6 = 7; 
    7 = 27; 
    8 = 39; 
} 

을 다음과 같이 생성을 기반으로 내가 값을 기준으로이 사전을 정렬 할. 그리고이 기사를 다음에 따라 수행 할 수 있습니다 그리고 내가 직접 대신 배열의 정렬 된 사전을 얻을 수 어쨌든 그래서 제 질문이 Getting NSDictionary keys sorted by their respective values 완벽하게 잘 작동과 키 배열이 값

(
    2, 
    6, 
    7, 
    1, 
    8, 
    5, 
    4, 
    3 
) 

에 따라 소트 반환합니다

+0

무엇을하기를 정렬 사전에 수행 할 수 있습니까? –

+0

NSDictionary는 키 액세스 시스템이고 값을 얻기위한 인덱스 액세스 시스템이 아니기 때문에 키 정렬에 신경을 쓰지 않습니다. – Larme

+0

[Swift에서 값순 사전 정렬] 가능한 중복 (http://stackoverflow.com/questions/24090016/sort-dictionary-by-values-in-swift) –

답변

0

에서, 두 개의 항목의 배열로 키 - 값 쌍을 저장하는 배열을 사용할 수있다. keyValuePair[0]이 키이고 keyValuePair[1]이 값입니다.

- (NSArray *)sortedDataFromDictionary:(NSDictionary *)dictionary { 
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:dictionary.count]; 

    for (NSNumber *key in [dictionary keysSortedByValueUsingSelector:@selector(compare:)]) { 
     NSArray *keyValuePair = @[key, dictionary[key]]; 
     [result addObject:keyValuePair]; 
    } 

    return [result copy]; 
} 

사전이 사전 설정되었을 때 (아마도 -viewWillAppear:).

self.sortedData = [self sortedDataFromDictionary:dictionary]; 

다음 -tableView:cellForRowAtIndexPath: 사용

NSNumber *key = self.sortedData[indexPath.row][0]; 
NSNumber *value = self.sortedData[indexPath.row][1]; 
0

저는 병렬 객체에 대한 큰 팬이 아니지만 키와 사전의 정렬 된 배열을 원할 수 있습니다.

초기에 사전이 설정되었을 때 (아마도 -viewWillAppear:).

self.sortedKeys = [self.dictionary keysSortedByValueUsingSelector:@selector(compare:)]; 

이어서 비평 오브젝트 용액 -tableView:cellForRowAtIndexPath: 사용

NSNumber *key = self.sortedKeys[indexPath.row]; 
NSNumber *value = self.dictionary[key];