I am trying to do a string comparison in iOS with a string obtained from a network stream.
The code that reads the stream is:
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable])
{
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0)
{
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
[self handleServerResponse: intCommand Response:output];
}else{
[self endComms];
}
}
The server at the other end always produces responses of 1024 bytes, with chr(0) being placed at the end of the data to fill the buffer.
When I do a string comparison:
if (strCut==@"B") {
//do something...
}
I always get a negative result, presumably because the string contaings the respo开发者_高级运维nse and lots of null characters.
I would like to be able to strip empty characters from the buffer when reading the response into the string, but I not having any luck in doing this in iOS.
Help appreciated!
Thanks.
Dave
You're making a bad assumption about why your code is not working.
Change:
if (strCut == @"B")
to:
if ([strCut isEqualToString:@"B"])
For future reference never make assumptions - use a debugger or other tools to verify what the problem is. You might also want to consider reading an introductory book on Objective-C.
The problem is iOS is lower level them presumably what you're use to so the == is actually comparing addresses, not strings. What you want is this.
if ([strCut compare:@"B"] == NSOrderedSame) {
...
}
hope this helps.
精彩评论