isEqualToString always returns False

空扰寡人 提交于 2019-12-23 15:14:14

问题


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 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

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

Any help would be greatly appreciated. Thanks.

回答1:


I guess that they are of different encoding.

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");
}

Will print s1 == s3.



来源:https://stackoverflow.com/questions/28507991/isequaltostring-always-returns-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!