Xcode 为什么iPhone在view controller.m文件中执行这两个if语句?

Xcode 为什么iPhone在view controller.m文件中执行这两个if语句?,xcode,iphone-sdk-3.0,Xcode,Iphone Sdk 3.0,当调用iAction登录时,它应该使用来自SOAP Web服务的响应true或false,这意味着用户无权使用该应用程序。 我让它在得到响应后使用这些if语句,但出于某种原因,它同时运行true和false if { [soapResults appendString: string]; NSLog(soapResults); if (soapResults = @"true") { UIAlertView *alert = [[UIAlertV

当调用iAction登录时,它应该使用来自SOAP Web服务的响应true或false,这意味着用户无权使用该应用程序。 我让它在得到响应后使用这些if语句,但出于某种原因,它同时运行true和false if

{
    [soapResults appendString: string];
    NSLog(soapResults);

    if (soapResults = @"true")
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:soapResults delegate:self cancelButtonTitle:@"Try Again",nil otherButtonTitles:nil];
        [alert show];
        [alert release];
        [soapResults release];
        soapResults = nil;
        [loginIndicator stopAnimating];
        loginIndicator.hidden = TRUE;
        loggedinLabel.text = usernameField.text;
        loggedinLabel.textColor = [UIColor blackColor];
        NSLog(@"Valid Login"); 
    }
        if (soapResults = @"false")
        {
            NSLog(@"Invalid Login");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:soapResults delegate:self cancelButtonTitle:@"Try Again",nil otherButtonTitles:nil];
            [alert show];
            [alert release];
            [soapResults release];
            soapResults = nil;
            [loginIndicator stopAnimating];
            loginIndicator.hidden = TRUE;
        }





}

请帮助if语句中只有一个等号。这将字符串分配给
soapResults
变量,该变量导致if语句对字符串求值(它将始终为true)

相反,使用两个等号进行比较

if (soapResults == @"true")
if (@"true" == soapResults)
有些人通过总是将变量放在比较的末尾来避免这个常见问题

if (soapResults == @"true")
if (@"true" == soapResults)
这样,如果您忘记了第二个等号,将导致编译错误,更容易找到

更新:正如评论员善意地指出的那样,您不应该使用==运算符来比较Objective-C字符串。而是使用
isEqualToString
方法

if ([soapResults isEqualToString:@"true"])

[soapResults isEqualTo:@“真的”]也许?好眼力!无论如何,关于比较:最好使用[soapResults isEqualToString:@“true”],否则它将始终为false(因为等号不是比较Obj-C中字符串的好方法)。谢谢Aviad,我的Obj-C已经生锈了。我会更新你提到的帖子。