views:

114

answers:

1

Hi guys, I have an array i load with lots of data from an xml file. I am displaying this on a tableview and then when you click on say an author it goes through to display all their books.

At the minute my NSMutableArray has an entry for every each book with title, author and so on. So in the table of authors it display the authors name as many times as they have books. I want to group the array data so the table only displays each author once but the author contains an array of his books. Seems simple but I can't find a group method for arrays.

thanks peeps

+1  A: 

You can loop through the books array and create a new array for the authors. For each book, check if that author is already in the authors array using containsObject. But then you'd also have to worry about only showing that author's books from the books array when the user selects an author.

It's probably better to load the xml file into an NSMutableDictionary in the first place instead where the keys are the author names and the object for each key is an NSMutableArray of that author's books.

Then the author tableview would use the dictionary's keys as the data source (using array returned by allKeys which you can then sort if needed or use keysSortedByValueUsingSelector) and the books tableview would use the book array of the selected key.

If the data becomes too large to load into memory all at once, then you'll have to use other options such as SQLite.

DyingCactus
yeah, thanks thought they may be an easy function to group the array on a particular field.I have used a for loop to loop through the main array, and I fill an sub array for each group, but when i add this to the main array it adds the sub array as an object so when i change it next time it changes it for all references in the main array. Is there a way to copy the sub array into the main array so this doesn't happen? thanks
padatronic
By "main" array do you mean "books for all authors" and by "sub" array do you mean "books for a specific author"? Not sure why you would add the sub arrays back to the main array or what you mean by "change it next time". It might help if you post the code that creates the sub arrays and adds them back to the main array (add the code to your Question and not as a Comment). I do think the simpler and more direct solution is to use a NSMutableDictionary. This will automatically group the books by author for you.
DyingCactus
i have solved it by creating an array of objects and passing this back so i can get anything i need using each objects getter and setters!
padatronic