I've read that the best way of creating an index (the a-z at the side of a uitableview) is to set up an array of nsdictionaries, where each dictionary corresponds to a section, and a rowValue key contains an array of the rows.
NSDictionary
headerTitle => ‘A’
rowValues => {”Aardvark”, “Ape”, “Aquaman”}
NSDictionary
headerTitle => ‘B’
rowValues => {”Bat”, “Boot”, “Bubbles”} etc
But how can this be created from an array of all the row titles - {”Aardvark”, “Ape”, “Aquaman”, ”Bat”, “Boot”, “Bubbles”, "Cat", "Cabbage" etc} ...?
I recently had a similar objective and this is how I solved it. The advantage of this over Robin's solution is that it creates the index title array dynamically based on the content of your array and it won't include indices for empty sections (plus it's a little cleaner).
I created a category of
NSMutableDictionary
that takes an array of data as a parameter and returns anNSMutableDictionary
(we'll call itindexDictionary
and it should be an instance variable):The category method:
Then I create an
NSArray
instance variable to sort and store all the keys fromindexDictionary
:You now have everything you need to set up the index for your table. Implement the following methods (if something isn't self explanatory, just let me know):
The result is a table with an index that skips letters that have no associated data.
I was working on one project where I need dynamic solutions for same problem so I figure out this solutions which returns dictionary with only available sections. Hope it help someone.
This is the code that I have used in one of the recent projects.