프로그래밍/COCOA/Objective C

NSString to char* and back again

Subi Lee 2010. 2. 24.
반응형
출처: http://bobobobo.wordpress.com/2009/11/01/nsstring-to-char-and-back-again/

Here’s how you do it.

NSString to char*

NSString* nsstr = @"My NSString" ;
const char * cstr = [ nsstr cStringUsingEncoding:ASCIIEncoding ] ;

// There's also
const char * cstr2 = [ nsstr UTF8String ] ;

These are covered in the docs page for NSString, basically.

char * to NSString

// Here you simply want to use one of the static method constructors
const char * cstyleString = "HELLO!!" ;
NSString * nsstr = [ NSString stringWithUTF8String:cstyleString ] ;

Or an instance method
NSString * nsstr2 = [[ NSString alloc ] initWithUTF8String:cstyleString ]

(( just a note that any methods labelled with + method are static methods and methods labelled with - are instance methods ))

sprintf() for NSString

Use initWithFormat

[ [ NSString alloc ] initWithFormat:@"%s is %d years old", "Bobby", 45 ]

Convert NSString to NSData
     NSString* str = [[NSString alloc] initWithData:aData encoding:NSUTF8StringEncoding];

Convert NSData to NSString
     NSData* aData = [aStr dataUsingEncoding:NSUTF8StringEncoding];


int value1 = *(int *)[buffer bytes];

unsigned char source[] = {0x00, 0x00, 0x00, 0x01};
NSData *data = [NSData dataWithBytes:source length:4];

unsigned char target[4] = {0,};
[data getBytes:target length:4];
int i = (taget[0] << 24) + (target[1] << 16) + (target[2] << 8) + target[3];
반응형

댓글