I’m trying to get the basics of iOS programming down. I have an app that shows a random number when I click a button.. At least, that’s what I wanted to make. However, it doesn’t seem to be working out.
I have the following basic method which should set the text of myLabel to the return value of generateRandomNumber. However, it always returns 0. I think the syntax I’m using here is correct since it works for the commented parts:
-(IBAction)myBtnPressed:(UIButton *)sender
{
//[myLabel setText:@"test"];
//[myLabel setText:[NSString stringWithFormat:@"%g / 15", 3.14]];
[myLabel setText:[NSString stringWithFormat:@"%g / 15", [myModel generateRandomNumber]]];
}
The last line sets the label to display 0/15. However, in my model, I have the following code (‘static’ for now):
-(double)generateRandomNumber
{
randomNumber = 1.34;
return randomNumber;
}
It doesn’t return the 1.34 and I don’t understand why it doesn’t. Can someone clear this up?
Update
This is the code for my viewcontroller.m file:
#import "myViewController.h"
@implementation myViewController
-(MyModel *)myModel
{
if (! myModel) {
myModel = [[MyModel alloc] init];
}
return myModel;
}
-(IBAction)myBtnPressed:(UIButton *)sender
{
[myLabel setText:[NSString stringWithFormat:@"%g / 15", [myModel generateRandomNumber]]];
}
@end
Also, in the end, I want to make generateRandomNumber return a random number between 0 and 15. How would I do this? Would a simple line like:
int x = arc4random() % 16;
work for this? Or do I have to seed it in some way so it doesn’t always return the same values when I run the application?
Thanks in advance.
Almost certainly, you haven’t allocated and initialised the
myModelobject. You can send messages tonilwithout crashing but the return value will be 0.arc4random()doesn’t need a seed.Edit
Your init code looks OK but you are not calling int, in your
myBtnPressed:method, you need