UITextField - If Statement
still new to the iPhone SDK however I am loving it so far...
im just goign through a course, tutorial online and a little confused, I am trying to basically have a UITextField and a submitbutton(AKA:GO action button on the keyboard)
h file..
IBOutlet UITextField *InsertUITextFieldBox; // UITextField to input keystrokes..
IBOutlet UILabel *myLabel; // UILabel to show if answer is correct or incorrect..
}
-(IBAction)dropMyKeyboard; // Setup to Say go - and IB - DidEndonExit on my UITextField
my .m file
-(IBAction)dropMyKeyboard{
NSString *TypedinbyUser = [[NSString alloc] initWithFormat:@"%@", [InsertUITextFieldBox text]]; //saves data in uitextfield to a nsstring
NSString *CorrectAnswer = [[NSString alloc] initWithString:@"http://google.com"]; //answer to used to compare in if statement with uitextfield
开发者_开发技巧 [myLabel setText:TypedinbyUser]; // show what was typed in my user
//if statement, if what user types is correct to the CorrectAnswer, then display the following if right or wrong....
if (TypedinbyUser == CorrectAnswer) {
[myLabel setText:@"You Answered Correctly"];
}
[myLabel setText:@"You Answered Incorrectly"];
}
so yeh, when I run this, and typed in "http://google.com" in my textfield and press GO - my UILabel goes to "You Answered Incorrectly" when I know its exactly what I typed, as I copied and pasted it from my code, without the quotes, and also manually typed it in, and tried adding spaces before and after....
any help would be great as to what I am doing wrong.. thank you
Because you are comparing pointers to strings and not the strings themselves. The string you typed will be at a different memory location to the test string so will have a different pointer (even though the strings themselves will be identical).
Try something like
if([TypedinbyUser compare:CorrectAnswer]==NSOrderedSame)
{
// do something positive here....
} else {
// do something negative...
}
To check if two strings are the same or not, use - (BOOL)isEqualToString:(NSString *)aString
.
You can find detail information here: NSString Class Reference
For your case: if ([TypedinbyUser isEqualToString:CorrectAnswer]) {...}
What you're comparing is if two strings' memory location are the same or not (of corse they aren't), if you're coming from language such as Java, learn how pointer works.
Another to note is, for variable name, it should start with lower case by convention.
精彩评论