views:

75

answers:

1

I have two custom objects, "Phrase Book" and "Phrase", the Phrase Book has an array of phrases, and each phrase has a Title, Description (and a whole lot of other properties / methods). In otherwords:

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 into a UITableView, sorted Alphabetically by phrase title with section headers. For which I need "numberOfSectionsInTableView", "numberOfRowsInSection", "titleForHeaderInSection", "cellForRowAtIndexPath(row,section)"

I started to build custom functions to sort all the objects alphabetically into another array, do counts on all the letters, (i was actually doing this by creating an nsdictionary with a key for every letter of the alphabet, adding to the array assosciated with it, and then deleting any keys that had an array with the length of 0).

Those functions are fine, but they feel like they are doing alot of grunt work for what seems like it should be quite simple. Thoughts? :)

+1  A: 

You'd use an NSSortDescriptor and when you allocate and initialize it, you pick a key to sort on. In your case this is the phrase title. Code would look something like this.

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

Once you create a sort descriptor you can sort it like this.

[listOfTitles sortUsingDescriptors:[NSArray arrayWithObject:titleSorter];

There are a bunch of other methods, be sure to look up the NSSortDescriptor Class Reference but hopefully this will get you going in the right direction.

Convolution
That does a great job of sorting my array of objects, but it still leaves me with an object with an array ([0].Title = "a...", [1].Title = "a...", [2].Title="k...", [3].Title="m...") - how do I convert that into something I can ask 'number of sections' from?
jamie-wilson
For numberOfRows and numberOfSections you usually just return the count of the array containing the objects. So you have an array of 10 titles, you just return [arrayContainingTitles count]. Assuming each index of the array corresponds to a title for a section header, why don't you just iterate over each element in the array and return the object in the delegate method titleForHeaderInSection?
Convolution
That's been a great help. Thanks heaps :)
jamie-wilson