2

What I want to do, is when the app is loaded, the user see's a tip. I have about twenty of them and I want just a label to show them. I can show them in order, I just don't know how to show a different one every time. So is their a method to just go through an order every time the view is loaded?

so far i have done this

Made a tip lebel to be set

@property (weak, nonatomic) IBOutlet UILabel *tipLabel;

and im gunna set it in the view did load

@synthesize tipLabel;

- (void)viewDidLoad
{
    [super viewDidLoad];
    tipLabel.text = // What Do I put here to pick from my list of 20 strings? 
                                    (in order or random)

1 Answers1

2

You don't say where or how you are storing your list (or array) of 20 strings, but assuming it is a "NSArray" object with 20 strings, you could do something like this:

tipLabel.text = [arrayOfTips objectAtIndex: (arc4random() % [arrayOfTips count])];
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • I was actually planning on making 20 strings in ashamed to say. How would I make a array with 20 strings? –  Sep 08 '13 at 01:20
  • Try to use a NSArray of NSString objects. instead of a c-style array of c-style strings. Your code will be much more pleasant to work with. [Here is a related question showing how to create an array of strings for iPhone](http://stackoverflow.com/questions/1602572/how-to-create-an-array-of-strings-in-objective-c-for-iphone). – Michael Dautermann Sep 08 '13 at 01:23
  • The problem with using modulus 19 instead of 20 is that it will generate an int in the range (0,18) when you want one in the range (0,19) for an array of 20 strings. So, you actually want `arc4random() % 20`. – Jsdodgers Sep 08 '13 at 01:24
  • 2
    Or even better would be `arc4random() % [arrayOfTips count]` so that you get a random one out of the whole range no matter how many items are in the array. – Jsdodgers Sep 08 '13 at 01:26
  • Very nice catch & suggestion Mr. Dodgers, I'll add that to my answer now. – Michael Dautermann Sep 08 '13 at 01:27
  • he also asked for "random" in addition to "in order", @Jeremy. – Michael Dautermann Sep 08 '13 at 03:44