views:

1440

answers:

4

I'm trying to create an array of strings that can be randomized and limited to a certain x number of strings.

If the array could be randomized I could pick the first x strings and that would work fine.

I'm trying to use code like this currently

NSString *statements[9];
statements[0] = @"hello";

This seems to work but the array seems to be full of rubbish data.

Can someone help me in the right direction. (is the memory allocation being done in the wrong way?

Thanks

+2  A: 

All C auto arrays like that will be full of garbage until you fill them. As long as it isn't getting filled with garbage later, everything is working as expected. However, Cocoa includes the NSArray class which is more common to use for arrays of objects (since it does proper memory management and works with the rest of the framework and all that).

Chuck
+10  A: 

Do you want an array with nine strings in it?

[NSArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", nil]
Justin Gallagher
Don't forget to end your array with nil.@"lastString", nil];(it may just be my iPhone that isn't showing me the end or you statement.
JoePasq
+3  A: 

This post contains a good array shuffle implementation: http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray

Populate your array with

NSArray *myArray = [NSArray arrayWithObjects:@"hello",@"world",@"etc",nil];
Chris Newman
Do I need to do [myArray release]; once I am done with the array (at the end of the method?Or should I leave it until the end of the app?
optician
You're not calling alloc to create the array so you don't need to release it.
Chris Newman
No you don't need to release something created with a message such as arrayWithObjects. See the apple memory management documentation http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html (in particular the "Memory Management Rules" and "Autorelease pools" sections)
Christopher Fairbairn
+1  A: 

Just a tip, it's not necessary to shuffle the contents of the array. Just randomize the access. For each card you want to pick from the deck, pick a random number and select the card at that index. Then, take the top card and place it where the card you just picked was.

If you really want to sort the array though, you can do it with very little code using -sortedArrayUsingSelector: where your comparison method returns NSOrderedAscending or NSOrderedDescending randomly.

NSResponder