Question

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

Was it helpful?

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).

OTHER TIPS

Variables declared in a method are local to that method. To share variables amongst methods in the same class make them instance variable, preferably by making them @propertys.

You get unused string error for str because it is not used after it is set.

assign the object str to your label. [words count] contains the count of the array not the value.

Make the str object global and then use that object to assign the value to the label.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top