ecarlin
ecarlin

Reputation: 1233

Objective-C Data Structure for Categorizing Items

I'm new to objective-c and I'm looking for a good data structure to allow for the categorization of items. Let's say I wanted to categorize types of food. The categories are meat, fruit, and vegetables. When a user inputs "apple" then I want to know that the apple belongs to the fruit category. In addition, these categories need to be mutable. So, if a user inputs an unknown food then they can assign it to a category and the category will be updated to remember this new type of food.

I have looked at using an NSMutableArray. My thinking goes that I would have an array for each category of food, and the elements of the array would be all the foods that fall in that category. I would then just search each array until I found a match.

The categories won't be too massive (< ~5,000 items in each), but large enough that I would like to have them sorted and take other considerations to allow for quick searching.

What are some good data structures to solve this problem?

Upvotes: 0

Views: 146

Answers (1)

Jack
Jack

Reputation: 133609

Objective-C provides 3 data structures which can be useful for your purpose, NSArray, NSSet and NSDictionary. These come also in the mutable flavour and NSSet offers also the NSOrderedSet subclass which can manage ordering.

What you should use depends on which kind of operations you are going to do mostly with your data:

  • you could have an NSMutableSet member for each food instance if you plan to assign multiple categories per element.
  • you could have a NSMutableArray of NSMutableSet instances, one per category and add the food to the specific NSMutableSet
  • you could have a NSMutableDictionary which maps each food to its category

But still it depends if you need fast lookup in one direction or in the other. Just think about that NSSet and NSDictionary provide fast lookup (so it's efficient to check if an element is contained in a NSSet or getting the value mapped to a specific key of a NSDictionary)

Upvotes: 2

Related Questions