0

My array contains three dictionaries per object of the array.

{
    avg = {
        avg1 = 50;
        avg2 = 60;
    };

    posts =         {
        alcoholContent = 450;
        name = "BBB";
        origin = United States;

    };

    reviews =  {

        rev1 = "Test review 1";
        rev2 = "Test review 2";
    };
}

{
    avg = {
        avg1 = 30;
        avg2 = 20;
    };

    posts =         {
        alcoholContent = 550;
        name = "AAA";
        origin = United States;

    };

    reviews =  {

        rev1 = "Test review 1";
        rev2 = "Test review 2";
    };
}

I want to sort array acceding by key "name" (of post dictionary). How can I do it?

I tried normal sorting methods using sort descriptors, but did not work

2
  • Sort descriptors should work. Could you post an example of what you did? Commented Jan 7, 2013 at 9:30
  • Thanks for answer. This is what I did NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; NSArray *sortedArray; sortedArray = [arrItems sortedArrayUsingDescriptors:sortDescriptors]; Commented Jan 7, 2013 at 9:32

1 Answer 1

1

Try sortUsingComparator:

[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDictionary *dict1 = obj1;
    NSDictionary *dict2 = obj2;

    NSString *string1 = [[dict1 objectForKey:@"posts"] objectForKey:@"name"];
    NSString *string2 = [[dict2 objectForKey:@"posts"] objectForKey:@"name"];

    return [string1 compare:string2];
}];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.