Lehman2020
Lehman2020

Reputation: 637

Sort a mutable array based on the sort of another mutable array?

Is there a way that I can sort an array based on an alphabetical sort that I did to another array? The practical use to this would be trying to associate an array with usernames to an array that contains those usernames' names. I have two separate lists containing this information and I need to alphabetically sort the users based on their name, but I need to access their username too. So in order to do this I'm trying to have both pieces of data within the table view cell and just show the name and hide the username.

I can't reverse sort the array containing the names to the usernames because if two people had the same names this would cause many problems.

I tried using a NSMutableDictionary but this didn't work. Any help would be extremely helpful!

Upvotes: 1

Views: 55

Answers (2)

Rob Napier
Rob Napier

Reputation: 299265

I have two separate lists containing this information

There's your problem. Don't use two data structures to store parts of one object.

Create a model object that represents a user and includes both the identifier and the name. Then everything is easy. The entire object is tiny:

@interface User
@property (nonatomic, readwrite, copy) NSString *identifier;
@property (nonatomic, readwrite, copy) NSString *name;
@end
@implementation
@end

Sorting objects by properties is simple.

Even if other parts of the system didn't use this object, I'd still create it as a "view model" object just for this view controller. (But it's probably better to treat it as a regular model object and use it throughout your system.)

Upvotes: 2

chaitanya.varanasi
chaitanya.varanasi

Reputation: 956

I'm not sure what you are really asking here.

But let me have a crack at this. Assuming you have an alphabetically sorted array of usernames. From that, why dont you create a NSHastable with <key,value>=<username,name>.

You also wont have the problem where two names will conflict with each other, assuming your usernames are unique.

Upvotes: 0

Related Questions