Chris Barry
Chris Barry

Reputation: 4594

How to create an Array of Strings in Objective c for iphone

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

Upvotes: 38

Views: 104527

Answers (4)

Johnny Oshika
Johnny Oshika

Reputation: 57482

As of Xcode 4.4, you can use Array Literals, which are much cleaner and easier to read. You no longer need to include 'nil'. For example:

NSArray *myArray = @[@"1", @"2", @"3", @"4", @"5"];

Upvotes: 64

NSResponder
NSResponder

Reputation: 16861

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.

Upvotes: 1

Justin Gallagher
Justin Gallagher

Reputation: 3232

Do you want an array with nine strings in it?

[NSArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", nil]

Upvotes: 75

Chuck
Chuck

Reputation: 237010

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).

Upvotes: 2

Related Questions