• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Sort Array
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Sort Array


  • Subject: Re: Sort Array
  • From: Ondra Cada <email@hidden>
  • Date: Sat, 16 Nov 2002 13:36:53 +0100

On Friday, November 15, 2002, at 06:11 , Lorenzo Puleo wrote:

I have a short list with "Name" and "Surname" fields.
I want to sort this list by "Surname".
How should I build the NSArray?
How should I use the NSArray methods?

Another 101, looks like ;)

An array of dictionaries seems to be the best solution, something like (typed into message, typos and bugs possible):

NSString * const Name=@"Name", * const Surname=@"Surname";

NSMutableArray *list=nil; // in practice would be rather some controller's property than a global

// just like these functions would be rather some controller's methods
void addPersonWithNameAndSurname(NSString *name,NSString *surname) {
if (!list) list=[[NSMutableArray alloc] init];
[list addObject:[NSDictionary/*or perhaps NSMutableDictionary -- depends on usage*/
dictionaryWithObjectsAndKeys:name,Name,surname,Surname,nil]];
}
NSString *nameOfPersonAtIndex(int i) {
return [[list objectAtIndex:i] objectForKey:Name];
}
static int compareDictBySurname(id left,id right,void *ctxt) {
// cast needed to get rid of a warning, since compare: is improperly declared in headers
return [(NSString*)[left objectForKey:Surname] compare:[right objectForKey:Surname]];
}
void sortPersonsBySurname {
[list sortUsingFunction:compareDictBySurname context:NULL];
}

Of course it all depends mainly on the usage: another possibility would be to store names as values into a dictionary keyed by surnames... The above solution though would be probably the most generic one.
---
Ondra Cada
OCSoftware: email@hidden http://www.ocs.cz
private email@hidden http://www.ocs.cz/oc
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.
References: 
 >Sort Array (From: Lorenzo Puleo <email@hidden>)

  • Prev by Date: Re: wakeup signals in OS X
  • Next by Date: [NSTableView] What is the purpose of highlightSelectionInClipRect:????
  • Previous by thread: Sort Array
  • Next by thread: Re: Sort Array
  • Index(es):
    • Date
    • Thread