【问题标题】:Matching an NSString and a UILabel's text [duplicate]匹配 NSString 和 UILabel 的文本 [重复]
【发布时间】:2017-06-08 20:52:43
【问题描述】:

我正在将用户输入的单词与秘密单词进行比较。我的if 语句测试正确的单词是否等于猜测的单词将不起作用。

@property (weak, nonatomic) IBOutlet UILabel *guesslet; //the guessed letter 
@property (weak, nonatomic) IBOutlet UILabel *Word;  //the ongoing guessed word
@property (weak, nonatomic) NSString *wrand;  //the correct word
@property (weak, nonatomic) NSString *letterguess;
- (IBAction)GuessButton;   //the button to guess the word

- (IBAction)GuessButton
{
  letterguess = guesslet.text;
  bool match = NO;
  char charInput = [guesslet.text characterAtIndex: 0];
  for(NSInteger i = 0; i < wrand.length; i++)
  {
    char tempChar = [wrand characterAtIndex: i];
    if (charInput == tempChar)
    {
      match = YES;
      NSRange InputRange = NSMakeRange(i, 1); //location, length
     Word.text = [Word.text stringByReplacingCharactersInRange: 
     InputRange withString: letterguess];
    }
    if(Word.text == randword)
    {
      UIAlertController *alert = [UIAlertController 
      alertControllerWithTitle:@”Winner!!”
      message:@”Great Job! You won!”
      preferredStyle:UIAlertControllerStyleAlert];
      UIAlertAction *okAction = [UIAlertAction
      actionWithTitle:@”Ok”
      style: UIAlertActionStyleDefault
      handler:^(UIAlertAction * action){
      }];
      UIAlertAction *cancelAction = [UIAlertAction
      actionWithTitle:@”Cancel”;
      style: UIAlertActionStyleDefault
      handler:^(UIAlertAction * action){
      }];
      [alert addAction:okAction];
      [alert addAction:cancelAction];
      [self presentViewController:alert animated: YES completion:nil];


    }
}

if(match == NO)

我做错了什么?

【问题讨论】:

  • = 是赋值,== 是相等性测试,但是因为您使用的是 Objective-C,所以您有引用,所以您是在比较引用,而不是那些引用的内容。您需要使用[Word.text isEqualToString:randword]。如果你刚开始使用 iOS 开发,我强烈建议你使用 Swift 而不是 Objective-C
  • 还有randword randword 是从哪里来的?你没有定义它我认为你正在尝试做[Word.text isEqualToString:wrand]

标签: ios objective-c if-statement nsstring


【解决方案1】:

使用 == 来比较会做一个指针(或引用)比较,如果你想比较实际的 NSString,你会想要使用类似的东西

if([Word.text isEqualToString:randword]) {

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 2011-11-25
    相关资源
    最近更新 更多