How to iterate through an NSArray of objects and create a new NSArray containing a subset of the original?
I am working on a basic iPhone app that pulls restaurant objects from a SQLite table, and displays them for the user in a table. My app is navigation based. I have no problems pulling the data from the SQLite database, and then sorting them. That I am able to do no problem. Each restaurant object has various properties, like "name", "address", "category" (i.e. the type of restaurant like greek, italian), and others. Now, after retrieving the records from the database, I am able to successfully put them into an NSMutableArray, and then sort them into an NSArray.
My question is, using this NSArray (or the original NSMutableArray), I'd like to create another array, with the first index containing "All", and then each remaining index contain the unique name of the category of restaurant from the original list, sorted in alphabetical order, and then present this as a table to the user on the next screen. From this table, if the user selects "All", the user will be taken to another screen displaying another table where they can see all the restaurants, regardless of genre.
If however, the user selects a particular category from the available list, the user will be taken to a scre开发者_StackOverflowen that displays a table composed of only those restaurants of that type (e.g. only Italian restaurants, only Chinese restaurants, only Thai restaurants). How would I go about doing this? Any ideas or suggestions?
One possible algorithm outline:
- Iterate over your NSMutableArray (e.g.
for(item in array
)) inserting the category property of each item into anNSMutableSet
(or anNSCountedSet
if you'd also like the number of times each category occurs) - Use the
NSSet
sortedArrayUsingDescriptors:
method to obtain a sorted array of the categories. - Add the All entry in whatever way suits
精彩评论