Search code examples
objective-cioscocoa-toucharc4random

How to randomise words


Im trying to display a word picked at random on an action from my array

Ive looked at Randomize words but still not getting it to work.

My label text is _answer

in my viewDidLoad:

NSArray *words = [NSArray arrayWithObjects: @"Blue", @"Green", @"Red", nil ];
NSString *str=[words objectAtIndex:arc4random()%[words count]];

under my action method:

 [_answer setText:[NSString stringWithFormat:@"%d", arc4random()%[words count]];

I get an unused string error for str

And in my action method I have an error use of undeclared identifier "words" but its in the viewDidLoad


Solution

  • Scope. The variables you created in your viewDidLoad method (words, str) are only valid inside that method (that is their scope). If you want to use them in another method, such as your 'action' method, you need to declare them in the class scope as a member variable/property.

    As an example, in your .h file:

    @interface ExampleViewController : UIViewController
        @property(nonatomic) NSString *answer;
        // ... your other stuff ...
    @end
    

    In your .m file:

    @synthesize answer;
    - (void)viewDidLoad
    {
        NSArray *words = [NSArray arrayWithObjects: @"Blue", @"Green", @"Red", nil ];
        self.answer = [words objectAtIndex:arc4random()%[words count]];
        [super viewDidLoad];
    }
    

    Finally, still in .m, your action:

    [_answer setText:self.answer];
    

    You can also just decalre it as a member variable (not a property).