2

I have a NSArray containing some objects.

NSArray *firstArray = [NSArray arrayWithObjects:obj, plop, color, shape, nil];

Now I have another NSArray containing only objects from the first NSArray, but not in the same order.

NSArray *secondArray = [NSArray arrayWithObjects: shape, color, plop, nil];

I would like to sort the secondArray in the same order that in the firstArray.

I want secondArray to be :

  • plop
  • color
  • shape
Blaszard
  • 30,954
  • 51
  • 153
  • 233
Aladin
  • 115
  • 2
  • 10

2 Answers2

1

NSArray is already ordered so you can use it at your advantage: why just don't you search what objects are inside the firstArray but not inside the secondArray then remove then from the first array ?

NSMutableArray *arrayObjectsInFirstArrayNotInSecondArray = [NSMutableArray arrayWithArray:firstArray];
[arrayObjectsInFirstArrayNotInSecondArray removeObjectsInArray:secondArray];

NSMutableArray *solution = [NSMutableArray arrayWithArray:firstArray];
[solution removeObjectsInArray:arrayObjectsInFirstArrayNotInSecondArray];
thomas.g
  • 3,894
  • 3
  • 29
  • 36
0

Normally this is the kind of thing for which I'd automatically point people to Apple's NSSortDescriptor Class, but it sounds like what you are doing is very application & object specific.

If your shape, color and plop objects are true Cocoa objects (i.e. they respond to isKindOfClass selectors), you can go through each piece of your secondArray and create a new mutable array (let's call it thirdArray for argument's sake) and use enumeration on the elements of secondArray to insert each object into thirdArray in the format that you are looking for.

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • Thank you for your answer ;) Actually those objects come from the same Cocoa Class. I'll see that, thanks you ;) – Aladin Dec 25 '11 at 10:26
  • But is there a way to compare with [firstArray indexOfObject:(id)] ? – Aladin Dec 25 '11 at 10:39
  • Sure! You now know how to determine the type of whatever object you've stored in both `secondArray` AND `firstArray`. Or are you talking about the contents of each object that you've stored in the arrays (i.e. `NSString` comparing to another `NSString` or `NSNumber` or?)?? – Michael Dautermann Dec 25 '11 at 10:42
  • To sum up, I would like to sort the objects in 'secondArray' using their index in 'firstArray'. I don't really need to check their type ;) Do you understand ? ? ^^' (I'm a french 17 years old guy, it's hard to make myself understand sometimes, sorry ^^') – Aladin Dec 25 '11 at 10:49
  • Can't answer now but i did : [secondArray sortedArrayUsingComparator:^(id obj1, id obj2) { if ([firstArray indexOfObject:obj1] > [firstArray indexOfObject:obj2]) return (NSComparisonResult)NSOrderedDescending; else return (NSComparisonResult)NSOrderedAscending; }] It works ;) – Aladin Dec 25 '11 at 10:58