Aladin
Aladin

Reputation: 115

NSArray sorting thanks to another NSArray

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 :

Upvotes: 2

Views: 153

Answers (2)

thomas.g
thomas.g

Reputation: 3932

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];

Upvotes: 1

Michael Dautermann
Michael Dautermann

Reputation: 89549

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.

Upvotes: 0

Related Questions