0

I have made a custom keyboard in my app. When user presses spacebar, this code runs:

NSString *lastChar = [myTextField.text substringFromIndex:[myTextField.text length] -  1];

NSLog(@"lastChar is `%@`", lastChar);

if (lastChar != @" ")
{
   NSString *currentString = [NSString stringWithFormat:@"%@ ", myTextField.text];
   [myTextField setText:currentString];
}

And I make a check, if last symbol that user used was space, he won't be able to use it again (no need in my case). However, the code under the if statement still runing. So I've made a check with NSLog, and even if the last char was space, the code under the if statement executes. How does it happen? Can somebody point me on my foolish mistake? Thanks in advance.

UPDATE: Sorry, I always forget how to compare strings in Objective-C, I've already flagged the question, thank you everyone for your anwsers.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
SmartTree
  • 1,381
  • 3
  • 21
  • 40
  • Have you tried `if (lastChar != @" ")` ? (Adding another space to your if statement string). If not trying `if ([lastChar isEqualToString:@" "])` with or without an additional space. – jfuellert May 30 '13 at 17:47
  • shouldn't it be [myTextField.text length] - 2 ? – Vignesh May 30 '13 at 17:47
  • 2
    This has absolutely **nothing** to do with Xcode at all. –  May 30 '13 at 17:51
  • 1
    It should be noted that the same issue will arise in C, Java, and several other languages. – Hot Licks May 30 '13 at 18:01

3 Answers3

5

It's not the if statement: NSStrings in Objective C should be compared with the isEqualToString: method, not with the != or == operators, which check reference equality:

if (![lastChar isEqualToString:@" "]) {
    ...
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Instead of

if (lastChar != @" ")

Use

if (![lastChar isEqualToString:@" "])

As lastChar is not a char, it is an NSString object.

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
0

This has been asked a thousand times. You can't compare strings like that in Objective-C (and a lot of other languages too). You have to use the comparator method which is called isEqualToString:.

if (![lastChar isEqualToString:@" "]) {

}
DrummerB
  • 39,814
  • 12
  • 105
  • 142