On Jan 31, 2010, at 9:49 PM, Kyle Sluder wrote:

> On Sun, Jan 31, 2010 at 6:28 PM, Stuart Malin <stu...@zhameesha.com> wrote:
>> If I use +dataWithBytes:length: then I need to specify a length 1 greater, 
>> and that additional byte must be set to 0 (to null terminate the string). 
>> So, I could use NSMutableData, then -resetBytesInRange: to zero out the last 
>> byte, which requires creating an NSRange struct, and that all seems heavier 
>> than just using the C code.  But then, the processor is fast, and this is 
>> code that is run rarely, so optimizing isn't important.  I guess it is just 
>> a question of style...
> 
> This is not true. The data you provide does not need to be a
> null-terminated C string. Though I'd use Stephen's approach because
> you don't have to create a wrapper data object. Proof that it works:
> 
> #import <Foundation/Foundation.h>
> 
> int main(int argc, char **argv) {
>  char p[5] = {'H', 'e', 'l', 'l', 'o'};
>  NSString *s = [[NSString alloc] initWithBytes:p
>    length:5 encoding:NSUTF8StringEncoding];
>  NSLog(@"s = %@", s);
>  [s release];
>  return 0;
> }


Ah, in my desire to use a class factory method, I overlooked 
initWithBytes:length:encoding: which does exactly what I need. It is 
interesting to me that a class convenience method wasn't provided as such would 
replace the deprecated function. Also wish that the documentation for 
stringWithCString:length: suggested using this init method with autorelease. 
Anyway, thanks!

_______________________________________________

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

Reply via email to