开发者

If-Else statement is flip-flopped

开发者 https://www.devze.com 2023-03-17 13:45 出处:网络
I am creating an application in iOS SDK and the user must enter a password to access their content. I am using an If-Else statement to verify their password. Problem is, the If-else statement is worki

I am creating an application in iOS SDK and the user must enter a password to access their content. I am using an If-Else statement to verify their password. Problem is, the If-else statement is working backwards, not like it should. For example: If The user enters the correct password then the label text says: Wrong Password. If the user enters the wrong password then the label text says: Password is Correct. That is the exact opposite of what I want it to do. Here is my code:

- (IBAction)isKey开发者_开发问答wordSecure:(id)sender {
    NSString *Key = [Keyword text];
    if ([Key compare:@"Password"]) {
        SecurityLevel.text=@"Keyword is Correct";
    } else {
        SecurityLevel.text=@"Keyword is WRONG";
    }
}

What did I do wrong? Any help would be appreciated! Thanks!


The NSString compare: method, like nearly all string comparison routines, returns zero if the strings compare equal (to be precise, it returns NSOrderedSame, which is zero).

You can replace your if condition with

if ([Key compare:@"Password"] == NSOrderedSame) {
    SecurityLevel.text=@"Keyword is Correct";

or use the isEqualToString: method instead.

All of this is in the documentation, with which you should familiarize yourself.


Take a look at the documentation for -[NSString compare:]; it doesn't return a boolean, but rather a NSComparisonResult. The value it returns is zero if the two strings are equal, which is equivalent to NO. You should use isEqualToString: instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消