Randomizing Alert view text for Objective C - objective-c

I am new to programming. I am having trouble finding out what all is wrong with this. It is an alert view that i am trying to randomize the text displayed in the message.
-(void)alert:(id)sender{
int randomNumber;
randomNumber = (randomNumber() %3 + 1);
NSLog(#"%i", randomNumber);
if (randomNumber == 1) {
self.YouWin.text = [NSString stringWithFormat:#"You Win"];
}
else if (randomNumber == 2) {
self.YouWin.text = [NSString stringWithFormat:#"You Lose"];
}
else if (randomNumber == 3) {
self.YouWin.text = [NSString stringWithFormat:#"Tie"];
}
NSLog(#"%#",YouWin);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Hello" message:[NSString stringWithFormat:#"%#",YouWin] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
button.hidden = YES;

Try this one:
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Hello"
message:self.YouWin.text
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
You needed text-value stored in YouWin, but you passed the YouWin object itself.
*Note: you can use arc4random() for generating random numbers.

There are many good suggestions; I agree with AKB8085.
Replacing the randomNumber() with arc4random() will help at compile time.
But you might want to re-think implementing a random number generator. The reason is in fairness to your user. I pose the question, “Is it fair to assume you want your user to guess a number with this large of a number range?”
Did you Know?
Using the arc4random(3), rand(3), or random(3) you are using a C function.
You are asking the user to guess a number with the following ranges:
arc4random(3) = 0 to 4294967296
rand(3) and random(3) that top out at a RAND_MAX of 0x7fffffff (214748647)
To help in answering your question, answer the following requirement questions:
Is there a min/max range restraint?
What type of compelling delays will happen
by using arc4random(3), rand(3), or random(3)?
Is using NSArray like in the Fisher–Yates_shuffle a better answer?
SUGGESTION:
Read an article on random numbers and NSArray.
NOTE:
Random numbers tend to task the compiler and your user experience will be hindered.

As Anoop noted you are using stringWithFormat but you're not providing a format string at all.
You should do
[NSString stringWithFormat:#"%#", #"You Win"];
but that's extremely redundant, although correct, and it's totally equivalent to just using #"You Win".
Also an advice for the general approach on the problem. Instead of having a big if-else statement, it's better to store all your string into a data structure and then randomly access to it.
In code this would translate to
NSArray * outcomes = #[ #"You Win", #"You lose", #"Tie" ];
int randomIndex = arc4random_uniform(outcomes.count);
NSString * randomOutcome = outcomes[randomIndex];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Hello"
message:randomOutcome
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
button.hidden = YES;
Note the usage of arc4random_uniform() that gives you back a random number between 0 and the argument provided, excluded.

Replace
randomNumber = (randomNumber() %3 + 1);
with
randomNumber = arc4random() %3 + 1;
Also use this...
if (randomNumber == 1) {
self.YouWin.text = [NSString stringWithFormat:#"You Win"];
}
else if (randomNumber == 2) {
self.YouWin.text = [NSString stringWithFormat:#"You Lose"];
}
else if (randomNumber == 3) {
self.YouWin.text = [NSString stringWithFormat:#"Tie"];
}
NSLog(#"%#",YouWin);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Hello"
message:self.YouWin.text
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
button.hidden = YES;

Related

Error message on Xcode that I don't understand

I am getting an error message on my Xcode - Objective C.
Arithmetic on pointer to interface "UILabel", which is not constant size for this architecture and platform.
if([self checkforwin]){
NSString*winner = nil;
if (playertoken==1)
winner =#"Player 2 Wins";
_result1 = _result1+1
else if (playertoken==2)
_result2 = _result2 +1
winner =#"Player 1 Wins";
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Result"
message: winner
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles: nil];
[self resetboard];
[_audioPlayer play];
[alert show];
Any Ideas how to get rid of them??
The error shows on both the result1 and result2. Trying to add a score to my game.
Use parenthesis while using condition. Also don't set string to nil, set it with empty string #""
if([self checkforwin]){
NSString *winner = #"";
if (playertoken==1) {
winner =#"Player 2 Wins";
_result1 = _result1 + 1;
}
else if (playertoken==2) {
winner =#"Player 1 Wins";
_result2 = _result2 + 1;
}
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Result"
message: winner
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles: nil];
[self resetboard];
[_audioPlayer play];
[alert show];
}
You are trying to add 1 to the UILabel. You need an integer variable to do the increment. Either declare the _result 1 and 2 as int type variable or declare a int variable and increment it, and pass it to UILabel .text property
_result1 = _result1+1
here _result1 must be a integer variable.
You need to something like:
Declare the result1 as int,
#property(assign) int result1;
and this line should be fine
_result1=_result1+1;

Objective-c function

I'm trying to create a function in order to save some code, however I have no idea how I should do it.
if (count > 100 && count < 120)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Time is up!"
message:[NSString stringWithFormat:#"You're really good at this! You scored %i points", count - 1]
delegate:self
cancelButtonTitle:#"Play Again"
otherButtonTitles:nil];
[alert show];
}
else if(count > 120)
{
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:#"Time is up!"
message:[NSString stringWithFormat:#"TEACH ME MASTER, YOU'RE A GOD! You scored %i points", count - 1]
delegate:self
cancelButtonTitle:#"Play Again"
otherButtonTitles:nil];
[alert2 show];
}
else
{
UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:#"Time is up!"
message:[NSString stringWithFormat:#"Not very good, you scored %i points", count - 1]
delegate:self
cancelButtonTitle:#"Play Again"
otherButtonTitles:nil];
[alert3 show];
}
As you can see the code is very repetitive and I would like to create a function where I can change the value of the "alert" variable and the message string. So when I call the function I only enter the functions name and the value the alert variable should have, in this case; 1, 2 and 3 and the message text depending on what condition we are looking at.
So is there some way of doing this? There has to be, because repetitive code like this is never good looking! I would appreciate if someone could help me out, I've tried looking at some references but none of them made me get any closer to solving the problem.
Simply look at the duplicated functionality and examine the values that are different. In this case it's just the message:
NSString *message = nil;
if (count > 100 && count < 120)
{
message = [NSString stringWithFormat:#"You're really good at this! You scored %i points", count - 1];
}
else if(count >= 120)
{
message = [NSString stringWithFormat:#"TEACH ME MASTER, YOU'RE A GOD! You scored %i points", count - 1];
}
else
{
message = [NSString stringWithFormat:#"Not very good, you scored %i points", count - 1];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Time is up!"
message:message
delegate:self
cancelButtonTitle:#"Play Again"
otherButtonTitles:nil];
[alert show];
(Edit: You missed the value 120 which would have slipped through the cracks).
I am create a new function that creates a new alert with given message :
-(void)showAlertWithMsg:(NSString *)msg tag:(NSInteger)tag
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Time is up!"
message:msg
delegate:self
cancelButtonTitle:#"Play Again"
otherButtonTitles:nil];
alert.tag = tag;
[alert show];
}
To call this function write the below code:
if (count > 100 && count < 120)
{
[self showAlertWithMsg:[NSString stringWithFormat:#"You're really good at this! You scored %i points", count - 1] tag:1];
}
else if(count > 120)
{
[self showAlertWithMsg:[NSString stringWithFormat:#"TEACH ME MASTER, YOU'RE A GOD! You scored %i points", count - 1] tag:2];
}
else
{
[self showAlertWithMsg:[NSString stringWithFormat:#"Not very good, you scored %i points", count - 1] tag:3];
}
One more thing I am also pass the tag.So if you want to perform different operation for different alert.
You can set "title" property exactly for existing UIAlertView instance:
UIAlertView * alertView = [[UIAlertView allow] init...];
alertView.title = #"Some message here.";

Regular expression syntax in Objective-C

I have looked everywhere and can't find a solution that works for this.
I have:
- (BOOL) textFieldShouldEndEditing:(UITextField *)textField {
NSString *regEx = #"/^[1-9]\d*(\.\d+)?$/";
NSRange r = [textField.text rangeOfString:regEx options:NSRegularExpressionSearch];
if (r.location == NSNotFound) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Entry Error"
message:#"Enter only numbers or decimals"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[av show];
return NO;
} else {
return YES;
}
}
But the regular expression isn't working. I want it to only accept numbers and decimals. I know that there is some weird difference in code with regex where you have to double up on backslashes or something, but I couldn't figure it out.
Remove the [1-9] at the beginning as well as the forward slashes and escape the backslashes so it is just:
"^\\d*(\\.\\d+)?$"
See How can I escape this regex properly in Objective-C?

Checking for multiple variable value in Xcode

I am creating an iPhone app which is taking many values from the user and assigning them to variables.
I want to display an alert message if more than two of the variables' values are equal to zero.
Basically, if the user has two empty fields, it should show an alert stating that there is insufficient data.
Any idea how to do this?
Your question is a bit vague but what about
Find errors
Display an alert
Somewhere alone the lines of this pseudo code:
int errorCount = 0;
if(var1 == 0) {
errorCount++;
}
if(var2 == 0) {
errorCount++;
}
// check all variables...
// Show alert if there are any errors
if(errorCount > 0) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Title"
message:[NSString stringWithFormat:#"You have %d errors", errorCount]
delegate:nil
cancelButtonTitle:#"GoFightWin"
otherButtonTitles: nil, nil];
[alert show];
[alert release];
}

Not able to compare responseString in objective c

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"the response string is %#",responseString);
if ([responseString isEqualToString:#"No Data Available"] )
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message"
message:#"No data Avilable in server"delegate:self cancelButtonTitle:nil otherButtonTitles:
#"OK", nil];
[alert show];
[alert release];
}
in my connectiondidfinishloadin delegate method i have the above code. when the server replies there is no data , it does not go into the if loop for some reason. not sure why. any hint will be greatly appreciated.
Thank You.
ResponseString is probably null/nil and runtime knows that that if statement will b false because of this, so skips it. You should see this with your NSLog(#"the response string is %#",responseString);
On a side note, Charles is a good debugging tool for this- you can see the http info as it goes out and comes in.