Skip navigation

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 ]
Advertisements

One Comment

    • Anonymous
    • Posted October 6, 2015 at 11:58 am
    • Permalink

    Small fix: [ nsstr cStringUsingEncoding:ASCIIEncoding ] ; to [ nsstr cStringUsingEncoding:NSASCIIEncoding ] ;


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: