views:

29

answers:

1

I'm wanting to read a list of forenames and surnames from a plist I have created, and then randomly select both a forename and a surname for a 'Person' class.

The plist has this structure;

Root (Dictionary)
-> Names (Dictionary)
--> Forenames (Array)
---> Item 0 (String) "Bob"
---> Item 1 (String) "Alan"
---> Item 2 (String) "John"
--> Surnames (Array)
---> Item 0 (String) "White"
---> Item 1 (String) "Smith"
---> Item 2 (String) "Black"

I have been able to output all the keys for the dictionary, but I am unsure of how to grab the 'Forenames' or 'Surnames' key and then store this in an array.

The code to output all the keys is a simple output to the log.

ie;

// Make a mutable (can add to it) dictionary
NSMutableDictionary *dictionary;


// Read foo.plist
NSString *path      = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"foo.plist"];

dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];

// dump the contents of the dictionary to the console
for (id key in dictionary)
{
    NSLog(@"Bundle key=%@, value=%@", key, [dictionary objectForKey:key]);      
}

NSMutableArray *forenames;

// This doesn't work, it outputs an empty array
forenames = [dictionary objectForKey:@"Forenames"];
NSLog(@"Forenames:%@", forenames);

Questions;

  1. How do I make my NSMutableArray *forenames take the contents of the dictionary 'Forenames'?

  2. Once I have stored both the forename and surname in their own NSMutableArrays, I need to randomly select both a forename and a surname; what's the best way to do that?

The idea is that I can create a Person.m file with a Forename/Surname class variables and I can create randomly generated people.

Thanks.

+1  A: 

Based on the structure of your plist, I think you need to do one more level of dereferencing:

NSDictionary *names = [dictionary objectForKey:@"Names"];
NSMutableArray *forenames = [[names objectForKey:@"Forenames"] mutableCopy];
NSMutableArray *surnames = [[names objectForKey:@"Surnames"] mutableCopy];

Then you can use srandom and random to generate random indices into your arrays. The general way of generating a random number on [0,N) is this:

NSUInteger i = (NSUInteger)((random()/(double)RAND_MAX)*N);

Replace N above with a call to an array's count and you'll be set.

By the way, I can't see a reason for creating a mutable copy of the name arrays. I just wanted to illustrate how you'd do it. Also, you need to seed with srandom(time(NULL)); to get different random values each time your program runs.

warrenm
I'll try that. I wasn't aware I had to use mutableCopy on them, but I'll try it and see what happens. Thanks.
zardon
That worked great, I was able to randomize a firstname and a surname and dump them to the log.Thanks for your help. I think the mutableCopy stuff threw me.
zardon