Alex Catchpole
Alex Catchpole

Reputation: 7336

Trying to randomly select an NSArray element

I have this code here that I have used to attempt to randomly select an element in an array. But when I execute it outputs the place of an element instead of the string.

int main()
{
    NSString *random;
    NSArray *names = [NSArray arrayWithObjects:@"sam", @"joe", @"smith", nil];
    NSUInteger randomIndex = arc4random() % [names count];
    random = [names objectAtIndex:randomIndex];
    NSLog(@"%lu", (unsigned long)randomIndex);
    return 0;
}

I am looking to print the string and not the place of the element. Any help would be greatly appreciated.

Upvotes: 0

Views: 31

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

That can be done as follows:

NSLog(@"%@", names[randomIndex]);

Earlier versions of the language require an explicit method call:

NSLog(@"%@", [names objectAtIndex:randomIndex]);

Upvotes: 1

Related Questions