0

I have array that have dictionaries, for exp..

[
  {
    name : dilip
  },
  {
    address : ahmedabad
  },
  {
    name : ajay
  },
  {
    address : baroda
  },
  {
    name : ram
  },
  {
    address : dwarka
  },
  .
  .
  .
]

Now i want to sort this array alphanumerically,Like this..

(
    {
        address = ahmedabad;
    },
        {
        name = ajay;
    },
        {
        address = baroda;
    },
        {
        name = dilip;
    },
        {
        address = dwarka;
    },
        {
        name = ram;
    }
)

But if any Dictionary does not have name than it will be sorted using address,
Any suggestion that how can we do it?

I have tried following code, but not getting proper result,

 NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
 NSSortDescriptor * productTitleDescriptor = [[NSSortDescriptor alloc] initWithKey:@"address" ascending:YES];
 NSArray * sortDescriptors = [NSArray arrayWithObjects:brandDescriptor, productTitleDescriptor, nil];
 NSArray * sortedArray = [ary sortedArrayUsingDescriptors:sortDescriptors];

I have 1 idea, that add address string in name and than sort array and once array sorted than will change it back to address,
But want to know is there any other option or not.

0

1 Answer 1

1

Think this might do the trick

NSArray * sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary * _Nonnull obj1, NSDictionary *  _Nonnull obj2) {

    NSString * s1 = [obj1 objectForKey:@"name"];
    if(s1 == nil){
        s1 = [obj1 objectForKey:@"address"];
    }

    NSString * s2 = [obj2 objectForKey:@"name"];
    if(s2 == nil){
        s2 = [obj2 objectForKey:@"address"];
    }

    return [s1 compare:s2];
}];

havnt tested the code so may need some tweaking

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect, Thank you.

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.