Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isEqualToString always returns False

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

debugger SS Any help would be greatly appreciated. Thanks.

like image 953
Dave S Avatar asked Mar 18 '23 01:03

Dave S


1 Answers

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.

like image 172
yusuke024 Avatar answered Mar 27 '23 14:03

yusuke024