Becca Royal-Gordon
Becca Royal-Gordon

Reputation: 17861

How do I escape a Unicode character in my Objective-C source code?

I feel incredibly stupid for asking this, but the documentation and Google are giving me no love at all.

I have a Unicode character I want to insert into a string literal in the source code of my iPhone app. I know its hex value. What is the proper escape sequence to use? And for that matter, what obvious source of information am I overlooking that would have told me this?

Upvotes: 40

Views: 32794

Answers (5)

Alex
Alex

Reputation: 2468

Example:

NSString *stuff = @"The Greek letter Beta looks like this: \u03b2, and the emoji for books looks like this: \U0001F4DA";

Upvotes: 68

Ky -
Ky -

Reputation: 32083

A more modern approach:

I'm not sure when this feature was added to the language, but as of 2015, at least, Objective-C string literals can contain any Unicode character. For instance, I mark my log lines with emoji because their distinctive colors are an easier way for me to pick them out:

message:@" \n \n\t💳‼️ Error: %@"

So, if you have the character and not just the code point, and you want to use it in a static string and not dynamically generate it, this is a great approach, since you instantly know what character you're using just by looking at it.

Upvotes: 4

Khay
Khay

Reputation: 993

\ is the escape character in objective c, use it before the letter to be escaped like :

NSString temp = @" hello \"temporary.h\" has been inported";

Here if you print the temp string in textview or logs, you will see " being printed as well because we have used the \ before them which is the escape character

Upvotes: -4

Marc Charbonneau
Marc Charbonneau

Reputation: 40507

If you don't want to put it directly in your string you can use a format specifier like this:

[string stringByAppendingFormat:@"%C", 0x2665];

Upvotes: 11

Christoffer
Christoffer

Reputation: 12910

The proper escape sequence would be something along the lines of

wchar_t * str = L"\x0627";

See this question: character constant:\000 \xhh

Edit: Oh, sorry, I missed the iPhone and Objective-C tags. The above is valid for generic C/C++, but I have not worked with iPhone development so your mileage may vary.

Upvotes: 1

Related Questions