On 18 Apr 2011, at 03:54, Quincey Morris <quinceymor...@earthlink.net> wrote:
> > On Apr 17, 2011, at 13:09, JAMES ROGERS wrote: > >> char sndBuffer[65]; >> int j; >> >> characterIndex++; // is always sitting at the last character sent so >> advance to the next character in string. >> for (j = 0; j < 65; j++) { >> sndBuffer[j] = [string characterAtIndex:characterIndex]; >> characterIndex++; >> } >> sndBuffer[j] = 0x00; >> substring = [NSString stringWithUTF8String:sndBuffer]; >> >> It works flawlessly, but there oughta be a way without reverting to C? > > This code is just wrong, BTW. > > The return value from -[NSString characterAtIndex:] is 'unichar', which is a > 16-bit quantity, so assigning it to a 'char' variable isn't a good idea. > > Also, the return value is *not* a character, in the sense of being a Unicode > code point. It's an element of the UTF-16 representation of the string. That > means you can't just stop extracting elements at an arbitrary position, > without potentially breaking the current substring and/or the next substring. > > Either you're going to have to analyze the sequence of elements manually > according to the UTF-16 definition to find a good break point, or use > something like -[NSString rangeOfComposedCharacterSequence...] (which doesn't > do the same thing, but does guarantees a usable UTF-16 break point). > > Also, re-creating the NSString (substring) using a UTF-16 string but > pretending it's a UTF-8 string isn't going to work very well. > > Also, it matters what's going to happen to your substring next. The UTF-8, > UTF-16 and Unicode code point byte-lengths of a string are all different, so > your assumptions about what fits into a fixed-size buffer need to be > carefully re-examined. > I would suggest to convert the string into raw bytes, using NSString dataUsingEncoding: NSUTF8StringEncoding , then NSData -bytes, then transmit the bytes in appropriate chunks. On the receiving end: get some bytes, use NSMutableData appendBytes:length: and finally, when all data have arrived, use NSString initWithData:encoding: NSUTF8StringEncoding. Gerriet. _______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com