Csabi
Csabi

Reputation: 3043

Simple boolean test not working

Hi i have a problem i want to test if my string is not empty and not equals to string1 i wann do something but it do not works.

my code:

 NSUserDefaults *namePrefs = [NSUserDefaults standardUserDefaults];
 NSString *savedName = [namePrefs stringForKey:@"myKey"];

if ((savedName != nil)&&([savedName isEqualToString:@"string1"])){ //

        [self myFunction];

    } 

it do not enters when the savedName is nil it is ok

it enters when the value of it is not nil and not string1 it is also ok

but it enters when savedName is string1, WHY?

thanks for any help bye

Upvotes: 0

Views: 362

Answers (3)

zoul
zoul

Reputation: 104065

You’re simply missing the “not” in the conditional:

(savedName != nil) && ([savedName isEqualToString:@"string1"])

This will be true when savedName is not nil and equals given string. You want this instead:

(savedName != nil) && (![savedName isEqualToString:@"string1"])

Also note that you can drop the first part, since messages sent to nil objects return NO:

![nil isEqualToString:@"string1"] ≈ !NO ≈ YES

Therefore, a nil string is considered different from @"string1". Sounds logical.

Upvotes: 5

Kirby Todd
Kirby Todd

Reputation: 11546

Because you told it to here:

if ((savedName != nil)&&([savedName isEqualToString:@"string1"])){

change to:

if ((savedName != nil)&&(![savedName isEqualToString:@"string1"])){ //

Upvotes: 4

Iqbal Khan
Iqbal Khan

Reputation: 4617

yes it will enter if savedname =string1 then it will enter in the block because it is satifing ur conditon.

savedname !=nil true

savedname ==string1 true

then why should not it enter in the block. it will enter bcoz it satisfying ur condition.

Upvotes: 2

Related Questions