ingenspor
ingenspor

Reputation: 932

Sort NSMutableArray is same order as another NSMutableArray

I'm using a NSMutableArray *allObjectsArray; with dictionaries to fill a Table View with content.

Now I want to use a second NSMutableArray *userDataArray; (also with dictionaries) to display some user defined data in the same TableView.

To make a way for the dictionaries from the different arrays to recognize each other, they both have a string with key: "Name" with matching values.

So how can I write a code so that the userDataArray objects are in the same order as the allObjectsArray objects using the matching values from the "Name" key?

So when the cells are created, the [allObjectsArray objectAtIndex: indexPath.row] should now reprecent the same object as [userDataArray objectAtIndex: indexPath.row]

Upvotes: 0

Views: 91

Answers (2)

nielsbot
nielsbot

Reputation: 16022

Why don't you just associate the objects in userDataArray to the objects in allObjectsArray directly? For example, each object in allObjectsArray can have a userData field that points to the associated object in userDataArray

In any case, if you really want to sort them you can do this:

NSArray * descriptors = @[ [ NSSortDescriptor sortDescriptorWithKey:@"Name" ascending:YES ] ] ;
allObjectsArray = [ allObjectsArray sortedArrayUsingDescriptors:descriptors ] ;
userDataArray = [ allObjectsArray sortedArrayUsingDescriptors:descriptors ] ;

EDIT: To directly associate the dictionaries from userDataArray with those in allObjectsArray

For each object in allObjectsArray, since they're dictionaries, you can just do this

NSDictionary * dictionaryFromAllObjectsArray = ...
[ dictionaryFromAllObjectsArray setObject:associatedUserObject forKey:@"userObject" ]

Now they're associated...

Later:

NSDictionary * dictionaryAtIndex = [ allObjectsArray objectAtIndex:indexPath.row ] ;
NSDictionary * userDictionaryAtIndex = [ dictionaryAtIndex objectForKey:@"userObject" ] ;

Upvotes: 2

Phillip Mills
Phillip Mills

Reputation: 31016

The best way is to restructure your data so that you only have a single dictionary for any name and it combines the objects and keys that you currently have in your pair of dictionaries. That would mean only needing one array and once it's sorted you have the rows you need.

Upvotes: 1

Related Questions