【问题标题】:ios compare two NSStrings [duplicate]ios比较两个NSStrings [重复]
【发布时间】:2013-03-20 02:28:35
【问题描述】:

我有这个功能是为了检查来自 udp 连接的数据

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag 
{    
 NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *hello = @"hello";
if(response == hello){
    [self debugPrint:[NSString stringWithFormat:@"ok"]];
}
else{
    [self debugPrint:[NSString stringWithFormat:@"Read:  \n%@",response]];
}

    [response release];

}

我发送了一个“hello”,但它从不返回“ok”消息,它跳转到 else{}

谁能帮忙?谢谢

【问题讨论】:

    标签: ios nsstring udp


    【解决方案1】:

    这行代码 如果(响应 == 你好) 应该 if([响应 isEqualToString:hello]) 因为“==”比较对象“respone”和对象“hello”的地址

    【讨论】:

      【解决方案2】:

      为了比较你必须使用 isEqualToString 函数:

      NSString * str = @"oranges";
      BOOL res = [str isEqualToString:@"apples"];
      

      【讨论】:

        【解决方案3】:

        "isEqualToString:" 是一个方法,它接受一个指向 NSString 对象的指针 ("aString") 并将其与调用它的 NSString 对象进行比较。

        if ([thing1 isEqualToString: thing2])

        这里的“thing1”是一个指向 NSString 对象的指针,我们使用它的成员方法“isEqualToString:”来与 NSString 对象“thing2”进行比较。

        所以“thing1”不是一个参数,而是一个对象,它有一个名为“isEqualToString:”的成员方法(或函数,如果这更简单的话)

        - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag 
        {    
           NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
          NSString *hello = @"hello";
        // check like this
          if(response isEqualToString:hello){
            [self debugPrint:[NSString stringWithFormat:@"ok"]];
            }
          else{
            [self debugPrint:[NSString stringWithFormat:@"Read:  \n%@",response]];
            }
        
            [response release];
        
        }
        

        【讨论】:

        • 感谢您的回答,但您的代码无法正常工作,我尝试使用 NSLOG(response) 并在调试屏幕中打招呼,但 if 每次都返回 false。另外,如果我尝试类似: NSString *hello = @"hello"; NSString *hello2 = @"你好"; if([hello2 isEqualToString:hello]){} if 返回 true.. pf 我很困惑!
        猜你喜欢
        • 2012-10-25
        • 1970-01-01
        • 2023-03-29
        • 2013-02-06
        • 2014-11-12
        • 1970-01-01
        • 2013-11-24
        • 2013-08-30
        • 1970-01-01
        相关资源
        最近更新 更多