Sergey Grishchev
Sergey Grishchev

Reputation: 12051

Comparing NSString to UITextField text never gets called

I record the value of the text in my UITextField and I want to compare the text to the original text field value later. I try something like this, but I never get the NSLog to be displayed. Any ideas why?

defaultTopicText = topicTextField.text;
if ([topicTextField.text isEqualToString:defaultTopicText]){
    NSLog(@"YES");
}else{
    NSLog(topicTextField.text);
    NSLog(defaultTopicText);
}

The code looks exactly like you see it. The first line I assign the value and the other - I compare with it. And it's not being called.

EDIT:

The code itself IS getting called and I also get the same values when I put them in NSLog. Might the problem be that the text field contains @"\n" characters?

NSLog gives me this:

2013-03-18 20:45:22.037 myapp[524:907] 

Here comes the text
2013-03-18 20:45:22.039 myapp[524:907] 

Here comes the text

Upvotes: 1

Views: 882

Answers (3)

nsgulliver
nsgulliver

Reputation: 12671

Try to print out the value of the topicTextField.text and see what is shows. otherwise set the breakpoints to see if you are reaching to that particular line of code.

You coud also try comparing after removing the white spaces and new line, if there might be any

NSString *trimmmedText = [topicTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

if ([trimmmedText isEqualToString:defaultTopicText]){
    NSLog(@"YES");
}

Upvotes: 1

Grady Player
Grady Player

Reputation: 14549

I typed the following the figured out the answer... running this should give you your answer:

if(!defaultTopicText){
    NSLog(@"defaultTopicText is nil");
}else{
    NSLog(@"defaultTopicText is a: %@".[defaultTopicText classname]);
}

defaultTopicText = topicTextField.text;
if ([topicTextField.text localizedCaseInsensitiveCompare:defaultTopicText] == NSOrderedSame){
    NSLog(@"YES");
}else{
NSLog(@"\"%@\" != \"%@\"",defaultTopicText, topicTextField.text);
}

Then I realized: topicTextField.text can only not be the same object as itself using this comparison method if it is nil.

topicTextField.text has to be nil... so it ends up executing:

id var = nil;
[var isEqual:nil];

and the runtime makes that return 0;

... so fix your outlet to topicTextField

Upvotes: 0

CainaSouza
CainaSouza

Reputation: 1437

Try changing to this:

NSString *newString = [defaultTopicText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

if ([newString isEqualToString:defaultTopicText]){
    NSLog(@"YES");
}

Upvotes: 0

Related Questions