0

I want to sort my main array depending on the first_name in the array self.contacts

Code that is used to sort the array

-(void)Sort
{
     NSSortDescriptor *sdName = [[NSSortDescriptor alloc] initWithKey:@"first_name" ascending:YES];
     self.contacts = [NSMutableArray arrayWithArray:[self.contacts sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sdName, nil]]];
}

MyData

self.contacts = (
        {
            contact = {
                "first_name" = "Test R";
            };

            "last_met" = (
                {
                    "last_met_date" = "2014-10-09";
                }
            );
        },
        {
            contact = {
                "first_name" = "Test K";
            };

            "last_met" = (
                {
                    "last_met_date" = "2014-10-09";

                }
            );
        }
    )
1
  • Please add more information. Your question is very vague.
    – TMob
    Oct 10, 2014 at 8:55

2 Answers 2

1

Try with this sort descriptor:

descriptor = [[NSSortDescriptor alloc] initWithKey:@"contact.first_name" 
                                         ascending:YES];

The parameter key is actually a key path, and NSDictionary is KV compliant. You can write stuff like: [contacts[0] valueForKeyPath:@"contact.first_name"].

1

Looking on your code it looks like that you want to sort your contacts array, which is an array of dictionaries, the solution I provide here is for that case.

You can do it like this:

NSArray *sortedContactsArray = [self.contacts sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSString *first_name1 = [obj1 valueForKeyPath:@"contact.first_name"];
    NSString *first_name2 = [obj2 valueForKeyPath:@"contact.first_name"];

    return [first_name1 compare:first_name2];
}];

Note, that it could be not safe and optimal, but that's just one of the ways to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.