Running a loop in a thread in an action.

Discussion in 'iOS Programming' started by NaughtyOttsel, Sep 21, 2008.

  1. NaughtyOttsel macrumors newbie

    Joined:
    Sep 21, 2008
    #1
    Ok here goes.

    I have an if statement running to check whether a number is in a Mutable Set, if yes then to regenerate the number, however this only works once and I do not want 100 different if Statements, which don't work. I have tried a do and do-while loop, which cause the app to freeze and a for loop which doesn't work.

    I've been told to run a thread to run the loop but I cannot get one to work in the first place.

    So two questions.

    Can I run a loop in a thread in a button action?

    How would I get this to work properly?

    Heres my button code:

    Code:
    - (IBAction)noButton {
    	
    	
    	
    	[previousGuess addObject:[NSNumber numberWithInt:thisNumber]];
    	NSString *theValue = [NSString stringWithFormat:@"%d", tries];
    	triesLabel.text = theValue;
    	++tries;
    	NSString *theNumber = [NSString stringWithFormat:@"%d", thisNumber];
    	thisNumber = random() % 100 + 1;
    	NSNumber *lol = [NSNumber numberWithInt:thisNumber];
    	if([previousGuess containsObject:lol] ==YES) {
    		NSLog(@"Number matched: %d",  [lol integerValue]); 
    		thisNumber = random() % 100 + 1;
    	}
    
    	
    	[previousGuess addObject:[NSNumber numberWithInt:thisNumber]];
    	isLabel.text = @"Is your number: ";
    	guessLabel.text = theNumber;
    }
    
     
  2. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    When I have an algorithm that is complicated and that I'm not getting to work I try to simplify it. I suggest you do the same.

    Forget about threading. Forget about updating the UI. Just write the algorithm in a method. Call the method from your app's applicationDidFinishLaunching: method. Strip out the extraneous stuff. Output the result with NSLog. Step through the code in the debugger until it works. Once you have something that works you can worry about integrating it into the UI. If your method needs fresh input you can simulate this by calling the method several times with different values or in a loop.

    If you can't see the big picture you need to draw a little picture.
     

Share This Page