给出以下Objective-C代码:
[NSString stringWithFormat:@"\n Elapsed Time \n Battery Level: \n Torque: \n Energy Used \n Energy Regenerated:\n Cadence: \n Battery Temp: \n Motor Temp: \n Incline: \n Speed MPH: \n Speed KPH:\n Avg Speed MPH: \n Avg Speed KPH:\n Distance Miles:\n Distance Km: \n Time Date Stamp:\n"];
在Xcode或任何代码编辑器中,是否可以避免使用非常长的字符串,必须通过在编辑器中滚动它来读取?
有没有办法将其分成多行?我发现,如果我尝试这样做,代码将无法编译,因为编译器到达行的末尾并且没有看到字符串的右引号("
)。
有没有人知道解决这个问题的方法?
答案 0 :(得分:90)
是的。编译器将为您连接相邻的字符串。
NSString *info = [NSString stringWithFormat:@"\n Elapsed Time \n"
"Battery Level: \n"
"Torque: \n"
"Energy Used \n"
"Energy Regenerated:\n Cadence: \n"
"Battery Temp: \n"
"Motor Temp: \n"
"Incline: \n Speed MPH: \n"
"Speed KPH:\n"
"Avg Speed MPH: %f \n"
"Avg Speed KPH:\n"
"Distance Miles:\n"
"Distance Km: \n"
"Time Date Stamp:\n"];
NSLog(info);
答案 1 :(得分:15)
这是一个有趣的功能,而不是一个有用的答案,但是......
// your code goes with that indentation (1 tab = 4 spaces)
NSString *myString = @"first line\
second line\
third line\
...\
last line";
// next lines of codes
但是你真的不得不考虑缩进,对上面的NSLog(@"%@", myString)
执行操作会导致:first linesecond linethird line...last line
。
现在考虑这个例子:
// your code goes with that indentation (1 tab = 4 spaces)
NSString *myString = @"first line\
second line\
third line\
...\
last line";
// next lines of codes
这会给:first lineXsecond lineXthird lineX...Xlast line"
,那些讨厌的X将被4个空格所取代(在这种情况下,制表师有4个空格,我无法正确格式化,对不起)。因此,额外的间距可以真正阻止您获得预期的结果。