简体   繁体   中英

Get value from array and put it in text label

I have a application where you press a button and when you pressed the button the label changes in a random word. But when i press the button my label disappear.

What should i do?

This is the code:

 if (sender == self.button) {

        NSString*path = [[NSBundle mainBundle]pathForResource:@"wordss" ofType:@"plist"];
        words = [[NSMutableArray alloc]initWithContentsOfFile:path];
        [self.randomLabel setText:[self.words objectAtIndex:arc4random_uniform([self.words count])]];
 }

Label is not disappearing the problem is you are setting empty string as the selected random value is returning null value.

NSString*path = [[NSBundle mainBundle]pathForResource:@"wordss" ofType:@"plist"];
words = [[NSMutableArray alloc]initWithContentsOfFile:path];
NSLog("%@",words);
NSString *string = [NSString stringWithFormat:[self.words objectAtIndex:((arc4random() % [self.words count]) + 0)]]
NSLog("%@",string);
[self.randomLabel setText:string];

check that nslog statement's are not null

Have you checked the output of:

arc4random_uniform([self.words count])

And, also since label can take NSString, so you need to cast int back to NSString. So, do like that:

NSString *myGeneratedRandNumber = [NSString stringWithFormat:@"%d", arc4random_uniform([self.words count])];

Then, set this string to your label, like that:

[myLabel setText:myGeneratedRandNumber];

Also note, working of this function:

The following will generate a number between 0 and 73 inclusive.

arc4random_uniform(74);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM