Pregunta

I have a dictionary that stores student id as the key, and their display name as the key for a subdictionary called "display". The dictionaries look something like this:

id-1:
  display: mark
id-2:
  display: alexis
id-3:
  display: beth

I would like the list to sort into two arrays, one for the key and one for the value, which would look something like this

key   value
id-2  alexis
id-3  beth
id-1  mark

I currently have this code:

-(void)alphabetize {
    PlistManager *pm = [[PlistManager alloc] init];
    NSMutableDictionary *students = [pm getStudentsDict:ClassID];;
    NSMutableArray *keyArray = [[NSMutableArray alloc] init];
    NSMutableArray *valArray = [[NSMutableArray alloc] init];

    for (id key in students) {
        [keyArray addObject:key];
        [valArray addObject:[[students objectForKey:key] objectForKey:@"display"]];
    }

    NSSortDescriptor *alphaDescriptor = [[NSSortDescriptor alloc] initWithKey:@"DCFProgramName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
    NSArray *sortedValues = [valArray sortedArrayUsingDescriptors:[NSMutableArray arrayWithObjects:alphaDescriptor, nil]];
    NSLog(@"%@", sortedValues);
}

but it throws an error when creating the sortedValues array.

If anyone could help me out or point me in the right direction, that would be greatly appreciated. Thank you!

¿Fue útil?

Solución

You have to sort the keys array based on the value they link to in the dictionary, then create the second array, although I feel like you don't really need the second array. One way of achieving what you want is using the sortUsingComparator: method in NSMutableArray, like this:

PlistManager *pm = [[PlistManager alloc] init];
NSMutableDictionary *students = [pm getStudentsDict:ClassID];
NSMutableArray *sortedKeys = [[students allKeys] mutableCopy]; // remember to manually release the copies you create
[sortedKeys sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSString *student1 = [students objectForKey:obj1];
    NSString *student2 = [students objectForKey:obj2];
    return [student1 compare:student2]; // this does a simple comparison, look at the NSString documentation for more options
}];
// at this point your sortedKeys variable contains the keys sorted by the name of the student they point to //
// if you want to create the other array you can do so like this:
NSArray *sortedStudents = [students objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];

// you can also iterate through the students like so:
for (int i = 0; i < sortedKeys.count; ++i)
{
    NSString *key = sortedKeys[i];
    NSString *student = [students objectForKey:key];
}

// or access directly:
NSString *studentAtIndex3 = [students objectForKey:sortedKeys[3]];

// always remember to release or autorelease your copies //
[sortedkeys release];

Hope it helps.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top