本文翻译自:How to split a string literal across multiple lines in C / Objective-C?
I have a pretty long sqlite query: 我有一个很长的sqlite查询:
const char *sql_query = "SELECT statuses.word_id FROM lang1_words, statuses WHERE statuses.word_id = lang1_words.word_id ORDER BY lang1_words.word ASC";
How can I break it in a number of lines to make it easier to read? 如何在多行中打破它以便于阅读? If I do the following: 如果我执行以下操作:
const char *sql_query = "SELECT word_id
FROM table1, table2
WHERE table2.word_id = table1.word_id
ORDER BY table1.word ASC";
I am getting an error. 我收到了一个错误。
Is there a way to write queries in multiple lines? 有没有办法在多行中编写查询?
#1楼
参考:https://stackoom.com/question/3LPy/如何在C-Objective-C中跨多行拆分字符串文字
#2楼
I am having this problem all the time, so I made a tiny tool to convert text to an escaped multi-line Objective-C string: 我一直有这个问题,所以我做了一个小工具将文本转换为转义的多行Objective-C字符串:
http://multilineobjc.herokuapp.com/ http://multilineobjc.herokuapp.com/
Hope this saves you some time. 希望这能为您节省一些时间。
#3楼
There's a trick you can do with the pre-processor. 你可以用预处理器做一个技巧。
It has the potential down sides that it will collapse white-space, and could be confusing for people reading the code. 它有潜在的缺点,它会崩溃白色空间,并且可能会让阅读代码的人感到困惑。
But, it has the up side that you don't need to escape quote characters inside it. 但是,它有一个好处,你不需要在其中转义引号字符。
#define QUOTE(...) #__VA_ARGS__
const char *sql_query = QUOTE(
SELECT word_id
FROM table1, table2
WHERE table2.word_id = table1.word_id
ORDER BY table1.word ASC
);
the preprocessor turns this into: 预处理器将其转换为:
const char *sql_query = "SELECT word_id FROM table1, table2 WHERE table2.word_id = table1.word_id ORDER BY table1.word ASC";
I've used this trick when I was writing some unit tests that had large literal strings containing JSON. 当我编写一些包含JSON的大型文字字符串的单元测试时,我已经使用过这个技巧。 It meant that I didn't have to escape every quote character \\". 这意味着我没有必要逃避每个引用字符“。
#4楼
Extending the Quote idea for Objective-C: 扩展Objective-C的引用思路:
#define NSStringMultiline(...) [[NSString alloc] initWithCString:#__VA_ARGS__ encoding:NSUTF8StringEncoding]
NSString *sql = NSStringMultiline(
SELECT name, age
FROM users
WHERE loggedin = true
);
#5楼
You can also do: 你也可以这样做:
NSString * query = @"SELECT * FROM foo "
@"WHERE "
@"bar = 42 "
@"AND baz = datetime() "
@"ORDER BY fizbit ASC";
#6楼
You could also go into XCode -> Preferences, select the Indentation tab, and turn on Line Wrapping. 你也可以进入XCode - > Preferences,选择Indentation选项卡,然后打开Line Wrapping。
That way, you won't have to type anything extra, and it will work for the stuff you already wrote. 这样,您就不必再输入任何额外内容,它将适用于您已编写的内容。 :-) :-)
One annoying thing though is... 但令人烦恼的是......
if (you're long on indentation
&& short on windows) {
then your code will
end up squished
against th
e side
li
k
e
t
h
i
s
}