isEqualToString 总是返回 False [英] isEqualToString always returns False

查看:76
本文介绍了isEqualToString 总是返回 False的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我开始之前,这里有一些背景知识,基本上我们希望将 UDP 响应与存储在我们应用程序的 Parse 数据库中的字符串进行比较.这个问题是我似乎无法让 isEqualToString 函数将字符串视为相等.这是我现在运行的代码,我尝试了一些在其他问题中看到的变通方法,但它仍然不起作用.

A little background here before I get started, basically we are looking to compare a UDP response with a string stored in Parse's database for our app. This issue is that I can't seem to get the strings to be considered equal by the isEqualToString function. Here's the code I have running now, I have tried a few work-arounds I've seen in other questions but it still doesn't work.

- (BOOL) onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port
{
    if(tag == TAG_SINGLE_GRILL)
    {
        NSString *grillId = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        if(grillId.length > 11)
        {
            grillId = [grillId substringToIndex:11];
        }
        grillId = [NSString stringWithFormat:@"%@", grillId];
        if([grillId hasPrefix:@"GMG"])
        {
            for(int i = 0; i < [parseGrills count]; i++)
            {
                NSString *parseGrillId = [[parseGrills objectAtIndex:i] grillId];
                parseGrillId = [NSString stringWithFormat:@"%@", parseGrillId];
                //If we match the id, add it to found grills
                if([grillId isEqualToString:parseGrillId])
                {
                    //do stuff
                }
            }
        }
        NSLog(@"Grill ID : %@", grillId);
    }
    return TRUE;
}

parseGrills 是一个带有非常基本的 Grill 对象的 NSMutableArray,我使用合成作为属性,否则 .m 文件基本上是空的.

parseGrills is an NSMutableArray with a very basic Grill object, I use synthesize for the properties, otherwise the .m file is essentially empty.

#import <Foundation/Foundation.h>

@interface Grill : NSObject

@property (nonatomic) NSString* grillId;
@property (nonatomic) NSString* ipAddress;

@end

这是调试器返回 false 后的屏幕截图

Here's a screen shot of the debugger after it returns false

任何帮助将不胜感激.谢谢.

Any help would be greatly appreciated. Thanks.

推荐答案

我猜他们是不同的编码.

I guess that they are of different encoding.

我运行了这个实验,看到如果编码不同,它会返回NO.因此,尝试使用以下代码将 parseGrillId 转换为 utf8.

I have run this experiment and see that if the encoding is different, it will return NO. So, try converting parseGrillId to utf8 with the code below.

NSString *s1 = [NSString stringWithCString:"HELLO123" encoding:NSUTF8StringEncoding];
NSString *s2 = [NSString stringWithCString:"HELLO123" encoding:NSUTF16StringEncoding];
NSString *s3 = [NSString stringWithUTF8String:s2.UTF8String];

if ([s1 isEqualToString:s2]) {
    NSLog(@"s1 == s2");
}

if ([s1 isEqualToString:s3]) {
    NSLog(@"s1 == s3");
}

将打印s1 == s3.

这篇关于isEqualToString 总是返回 False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆