tags:

views:

26

answers:

2

Still working my way through this program. Next task on my to-do list is selecting random words from a pre-generated list. I've got the randomisation code sorted, but I now need to know the best way to store and retrieve words from my big list (and it is a fairly big list - over 220 words).

Since I'm designing for iPhone, memory is a paramount concern. Because of this I was hoping to avoid loading the whole file into memory. I'd much rather have the file laid out so that I can jump straight to an indexed position in the file and grab only the data I need. It would be nice if I could make use of the text file I already have with all the words in it, but I don't mind converting if there is benefit to some other method.

Anyone got any suggestions about the best way to do this?

-Ash

A: 

Don't worry about the storage space (the storage required is far less than you think). Use a PLIST (File > New File > Resource (Mac OS X) > Property List), and arrayWithContentsOfFile to make loading the words simple (define an array as the root item in the PLIST; Apple's documentation has further details). Then, simply:

srandom(time(NULL));
NSUInteger index = rand() % [array length];
NSString *word = [array objectAtIndex:index];
Kevin Sylvestre
Thanks! Alas, one solution only brings more problems, the new one being I just can't work out how to retrieve the full and proper filepath to my new .plist file so that I can load it in the first place. The filename is randomNames.plist, and it seems to be stored in a directory called Resources. This is my current code, any idea what's wrong with it?NSString *filePath = [[NSString alloc] initWithString: [[NSBundle mainBundle]pathForResource:@"randomNames" ofType:@"plist" inDirectory: @"Resources"]]; randomNames = [[NSArray alloc]initWithContentsOfFile:filePath];
Ash
Try removing the 'inDirectory:'. Shouldn't need it.
Kevin Sylvestre
A: 

Well, 220 words isn't exactly a big list :-) Let's say each word is long, say 20 characters. Then you're talking about a measly 4.4kB. So I wouldn't worry about the size here. As Kevin pointed out, [NSArray arrayWithContentsOfFile:...] is likely the easiest way (also have a look at [NSDictionary dictionaryWithContentsOfFile:...]).

But if your list is getting really big (say 10000 words) then I'd suggest you read up on SQLite which is also supported on the iPhone.

DarkDust