Method for sorting custom objects alphabetically in a UITableView

I have two user objects: Phrase Book and Phrase, in the Phrase Book there are many phrases, and each phrase has a name, description (and many other properties / methods). In other words:

PhraseBook.Phrases (NSArray) => Phrase (Subclass of NSObject) { Phrase.Title = "Phrase Title", Phrase.Description = "Phrase Description" }, Phrase (Subclass of NSObject) { Phrase.Title = "Phrase Title", Phrase.Description = "Phrase Description" } 

I need to get this in a UITableView, sorted alphabetically by the name of the phrase with section headers. Why do I need "numberOfSectionsInTableView", "numberOfRowsInSection", "titleForHeaderInSection", "cellForRowAtIndexPath (string, section)"

I started creating custom functions for sorting all objects alphabetically in another array, taking all letters into account (I actually did this by creating an nsdictionary with a key for each letter of the alphabet, adding to the array associated with it, and then deleting any keys that had an array with a length of 0).

These functions are great, but they feel like they do a lot of grunt work, as it seems like it should be pretty simple. Thoughts? :)

0
source share
1 answer

You would use an NSSortDescriptor , and when you select and initialize it, you select the key to sort. In your case, this is the name of the phrase. The code will look something like this.

 NSSortDescriptor *titleSorter= [[NSSortDescriptor alloc] initWithKey:@"phraseTitle" ascending:YES]; 

After creating the sort descriptor, you can sort it as follows.

 [listOfTitles sortUsingDescriptors:[NSArray arrayWithObject:titleSorter]; 

There are many other methods, be sure to look at the Link to the NSSortDescriptor class , but hopefully this will lead you to the right direction.

+4
source

All Articles