如何在Objective-C NSString中写特殊字符 [英] how to write special character in objective-C NSString

查看:63
本文介绍了如何在Objective-C NSString中写特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试编写此JSON时:

when I try to write this JSON:

{"author":"mehdi","email":"email@hotmail.fr","message":"Hello"}

在Objective-C中是这样的:

like this in Objective-C:

NSString *myJson=@"{"author":"mehdi","email":"email@hotmail.fr","message":"Hello"}";

它不起作用.有人可以帮我吗?

it doesn't work. Can someone help me?

推荐答案

您需要用反斜杠转义引号字符:

NSString *myJson = @"{\"author\":\"mehdi\",\"email\":\"email@hotmail.fr\",\"message\":\"Hello\"}";

否则,编译器会认为您的字符串文字在第一个 {之后立即结束.反斜杠在所得的NSString中不会以字符形式显示.它们只是作为编译器提示出现在其中,并从在编译期间的实际字符串中被删除.

Otherwise the compiler will think that your string literal ends right after the first {. The backslashes will not be present as characters in the resulting NSString. They are merely there as hints for the compiler and are removed from the actual string during compilation.

新手注意:当然,您可以通过目标C直接从文件中读取的JSON 字符串不需要任何转义!(JSON本身可能需要这样做,仅此而已.不需要在其ObjC端进行其他转义.)

Newbie note: JSON strings that you read directly from a file via Objective C of course do not need any escaping! (JSON itself may need such, but that's about it. No need for additional escaping on the ObjC-side of it.)

这篇关于如何在Objective-C NSString中写特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆