views:

34

answers:

1

What I am trying to do is create a an array of text strings, and I want to select a random text string out of this array, which I could normally do easily with an array. However, I would also like to be able to put them into categories, and when I select a random one, I would like to know what category it is in and do something different with it which is decided by the category it was in. I was thinking I could use keys in NSDictionary to decide the categories as in setting all the entries in a category to have the same key. But then I don't know how I could retrieve a random one from that dictionary and then know what the key was. I have never used NSDictionary so I don't know much about it so maybe what I just said doesn't make any sense.

It is also possible that I am approaching this in completely the wrong way, so if you have any other suggestions as to how to do what I described I would be open to that, and a pretty detailed code answer would be best if it is possible.

A: 

I would just fill the array with dictionaries, i.e.

{
  { category = Animals,
    name = Cat },
  { category = Vehicles,
    name = Helicopter },
  { category = Foods
    name = Pie },
  { category = Animals,
    name = Zebra }
}

and then select randomly from that array.

For a programmatic example:

theArray = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:@"Animals", @"category", @"Cat", @"name", nil],
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Vehicles", @"category", @"Helicopter", @"name", nil],
                                     // ...
                                     [NSDictionary dictionaryWithObjectsAndKeys:@"Animals", @"category", @"Zebra", @"name", nil],
                                     nil];

// ...

randomDict = [theArray objectAtIndex:(rand() % [theArray count])];
NSString *name = [randomDict objectForKey:@"name"];
NSString *category = [randomDict objectForKey:@"category"];
Noah Witherspoon
Thanks a lot that looks great!
Regan
When I try to use this I get a "initializer element is not a constant" error message for the line that says "nil];"
Regan
Make sure you have all your nested bits and commas sorted out. The assignment to 'theArray' is, in effect, all one long line.
willc2