tags:

views:

53

answers:

2

Hello,

I create an NSString using,

NSString *myString = [[NSString alloc] initWithBytes:someBuffer length:sizeof(someBuffer) encoding:NSASCIIStringEncoding];

I used NSLog to output myString and it displays "Hello".

If this is the case, then why does this fail.

NSString *helloString = @"Hello"

BOOL check = [myString isEqualToString:helloString];
+1  A: 

There are probably some trailing characters that you can't see when calling NSLog(). For example: whitespace, linefeeds or even '\0' characters.

Check [myString length] to see if it returns 5.

Philippe Leybaert
+5  A: 

Your myString variable is actually an NSString with a length of 64; the additional characters are probably undefined. What you most likely want to do is this:

NSString *myString = [[NSString alloc] initWithBytes:someBuffer length:strlen(someBuffer) encoding:NSASCIIStringEncoding];

This assumes a null-terminated C-string exists in your buffer.

Ben Gottlieb
Perfect. That works. You just need to add one casting operation as follows. Thank you. NSString *myString = [[NSString alloc] initWithBytes:someBuffer length:strlen((const char*)someBuffer) encoding:NSASCIIStringEncoding];
David
Sorry should be (const char *)
David
Or, better yet, [[NSString alloc] initWithCString:someBuffer encoding:NSASCIIStringEncoding].
Peter Hosey
That works too, but you still need to cast to const char *
David