Flatlyn
Flatlyn

Reputation: 2050

iOS For Loops Printing Array

I'm trying to use a for loop to pick letters from an array of letters and then add them to a variable which will then be printed to a Label.

I've written this code, which uses a random number generator to select a random letter from the array and then should join it variable password. However it wasn't displaying anything in Label so I set a breakpoint inside the for loop to see what was happening but it doesn't even seem to be getting into the loop at all, e.g. it doesn't break inside it.

Here is the code I'm using

- (void) tapRecog:(id)sender
{
    @autoreleasepool 
    {

        NSString *password;
        NSArray *alpha = [NSArray arrayWithObjects: @"a", @"b", @"c", @"d", nil];
        int i, ran;

        for(i = 0;i == 3;i = i + 1)
        {
            ran = arc4random() % 3;
            password = [password stringByAppendingFormat:[alpha objectAtIndex:ran]];

        }

        displayPassword.text = password;
    }
}

Upvotes: 0

Views: 13436

Answers (2)

Kristian Glass
Kristian Glass

Reputation: 38540

A few things. First, you never initialise password, so when (or if, as per my second point) the code in your for loop runs, you'll have a problem...

Consider instead:

NSString *password = @"";

Also the condition in your for loop is wrong - the second statement, where you have i == 3, is the condition that must be YES for the for loop to continue; I suspect you mean:

for (i = 0; i < 3; i++)

Upvotes: 4

El Guapo
El Guapo

Reputation: 5781

It's not getting into your loop because you telling your for loop to run while i == 3. In the first segment of your for loop you are setting i = 0, then you are saying run while i == 3. Change the i == 3 to i < 3.

Upvotes: 3

Related Questions