对iPhone软件开发工具包来说还是个新手,不过到目前为止我还很喜欢它……
我只是去通过一个课程,在线教程和一些困惑,我试图基本上有一个UITextField和一个提交按钮(也就是键盘上的GO操作按钮)
H文件..
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我的.m文件
-(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"];
}所以,是的,当我运行这个程序,在我的文本字段中键入"http://google.com“并按GO时-当我知道我键入的内容完全正确时,我的UILabel就会显示为”您回答不正确“,因为我从代码中复制并粘贴了它,没有引号,还手动键入了它,并尝试在前后添加空格……
如果我做错了什么,任何帮助都是很好的..谢谢
发布于 2011-08-03 06:58:50
因为您比较的是指向字符串的指针,而不是字符串本身。您键入的字符串将位于与测试字符串不同的内存位置,因此将具有不同的指针(即使字符串本身是相同的)。
试试像这样的东西
if([TypedinbyUser compare:CorrectAnswer]==NSOrderedSame)
{
// do something positive here....
} else {
// do something negative...
}发布于 2011-08-03 07:14:04
要检查两个字符串是否相同,请使用- (BOOL)isEqualToString:(NSString *)aString。
你可以在这里找到详细信息:NSString Class Reference
对于您的案例:if ([TypedinbyUser isEqualToString:CorrectAnswer]) {...}
您要比较的是两个字符串的内存位置是否相同(或不同),如果您来自Java等语言,了解指针是如何工作的。
另一个需要注意的是,按照惯例,变量名应该以小写字母开头。
https://stackoverflow.com/questions/6919693
复制相似问题