1

I'm new to Objective-C and currently I'm writing a Guess the Number single view application for Iphone. The "New Game" button currently runs this code.

- (IBAction)newGame:(id)sender {

NSString *guessANumber = @"Guess a number between 1 and 25!";
[output setText:guessANumber];
}

and the random method currently looks like this

-(int)Random {
int num;

num=(arc4random() % ((unsigned)25 + 1));
while (num == 0) {
    if (num == 0)
    {
    num=(arc4random() % ((unsigned)25 + 1));
    }
}    

return num;
}

Currently the method for when the player submits his/her guess is

- (IBAction)submitGuess:(id)sender {

int num = [self num];

for (int x = 1; x<=3;x++)
{

    if([textField.text intValue] > num)
        output.text=@"Too high.";
    else if([textField.text intValue] < num)
        output.text=@"Too low.";
    else if ([textField.text intValue] == num)
        output.text=@"You got it!";
    else 
        output.text= @"You lose. The number was %i.", num;


}

The turn system isn't implemented currently.

I'm new to Objective-C and I'm not sure how to get the random number in to the action that happens when the submit button is pressed.

Sorry for the newbie question.

edit: Thanks for the help, it is working now.

Snorf
  • 108
  • 1
  • 8

1 Answers1

1

You could make num an instance variable of the view controller. Something like:

@interface MyViewController : UIViewController
{
   int num;
}

Then your submit method would look like this

- (IBAction)submitGuess:(id)sender {
    // access your random value here and do something with it.
    [self num];
}

Here's a good pdf on learning objective-c. https://developer.apple.com/library/mac/documentation/cocoa/conceptual/objectivec/objc.pdf

Also, you might want to change the way you generate random numbers. Check this out: Generating random numbers in Objective-C

Community
  • 1
  • 1
Matt Becker
  • 2,338
  • 1
  • 28
  • 36