-1

i have this function in order to check coming data from a udp connection

- (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];

}

I send a "hello" but it never return the "ok" message, it jumps to the else{}

Can anyone help?thank you

man_or_astroman
  • 648
  • 1
  • 17
  • 39

3 Answers3

1

In order to compare you have to use the isEqualToString function:

NSString * str = @"oranges";
BOOL res = [str isEqualToString:@"apples"];
joan
  • 2,407
  • 4
  • 29
  • 35
0

this line of code if(response == hello) should be if([response isEqualToString:hello]) because "==" compares the address of object "respone" and object "hello"

haibarahu
  • 49
  • 8
0

"isEqualToString:" is a method which takes a pointer ("aString") to a NSString object and compares it to the NSString object it was called on.

if ([thing1 isEqualToString: thing2])

Here "thing1" is a pointer to a NSString object and we use it's member method "isEqualToString:" to compare it with the NSString object "thing2".

So "thing1" isn't an argument but an object which has a member method (or function if that's easier) called "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];

}
NewStack
  • 990
  • 8
  • 19
  • Thanx for your answer but your code is not working, i tryed to NSLOG(response) and i get hello in my debug sreen but the if return false every time. Also if i try something like: NSString *hello = @"hello"; NSString *hello2 = @"hello"; if([hello2 isEqualToString:hello]){} the if returns true.. pf im confused! – man_or_astroman Mar 30 '13 at 11:01