0

Think Inception. Say I have 2 objects A and B and each instance of A has a variable B and each B has an NSNumber variable.

I have an NSArray Array with instances of A inside it and I want to sort it based on the NSNumber variable within B. So the normal approach of going

NSArray *array = [[NSArray alloc] initWithObjects:a1,a2,a3,a4,a5,nil];

NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"b" ascending: YES];
array = [array sortedArrayUsingDescriptors: [NSArray arrayWithObject:sortOrder]];

just isn't going to cut it. Any ideas?

Lorenzo Ang
  • 1,202
  • 3
  • 12
  • 35

1 Answers1

2

The sorting should work fine with this approach as long as you use the proper key for comparison as follows:

NSArray *array = [[NSArray alloc] initWithObjects:a1,a2,a3,a4,a5,nil];

NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"b.nsnumbervar" ascending: YES];
array = [array sortedArrayUsingDescriptors: [NSArray arrayWithObject:sortOrder]];
user3435374
  • 1,296
  • 9
  • 7
  • Wait, it doesn't work :\ – Lorenzo Ang Jan 31 '15 at 06:15
  • The property key for sort descriptor needs to be accessed using key-value coding – user3435374 Jan 31 '15 at 06:24
  • Wait, sorry, I think my code is faulty. I'll check back in a bit :) – Lorenzo Ang Jan 31 '15 at 06:25
  • A key path is a string of dot separated keys that is used to specify a sequence of object properties to traverse. The property of the first key in the sequence is relative to the receiver, and each subsequent key is evaluated relative to the value of the previous property. For example, the key path address.street would get the value of the address property from the receiving object, and then determine the street property relative to the address object. – user3435374 Jan 31 '15 at 06:30
  • Yeah, okay, it worked. My code really was just faulty. Thank you :) – Lorenzo Ang Jan 31 '15 at 07:51