2011-02-25 62 views
4

當我將換行符插入字符串時,Xcode會引發各種錯誤。例如,這種失敗:如何在不破壞代碼的情況下拆分Objective-C中的字符串

if (newMaximumNumberOfSides > 12) { 
    NSLog(@"Invalid maximum number of sides: %i is greater than 
      the maximum of 12 allowed.", newMaximumNumberOfSides); 
} 

但這個工程:

if (newMaximumNumberOfSides > 12) { 
    NSLog(@"Invalid maximum number of sides: %i is greater than the maximum of 12 allowed.", 
      newMaximumNumberOfSides); 
} 

我更喜歡前者,因爲它清潔一下(更短的行),但代碼符。處理這個問題的最好方法是什麼? (Subquestion:是這樣在任何語法指南引用我搜索我的「換行」的所有書籍沒有效果。)

回答

7

所有這些應該工作:在

NSString *s = @"this" \ 
     @" is a" \ 
     @" very long" \ 
     @" string!"; 

    NSLog(s); 


    NSString *s1 = @"this" 
     @" is a" 
     @" very long" 
     @" string!"; 

    NSLog(s1); 

    NSString *s2 = @"this" 
     " is a" 
     " very long" 
     " string!"; 

    NSLog(s2); 

    NSString *s3 = @"this\ 
is a\ 
very long\ 
string!"; 

    NSLog(s3); 
8
if (newMaximumNumberOfSides > 12) { 
    NSLog(@"Invalid maximum number of sides: %i is greater than " 
      "the maximum of 12 allowed.", newMaximumNumberOfSides); 
} 
2

字符串常量C不能包含換行符。要報價http://gcc.gnu.org/onlinedocs/cpp/Tokenization.html

沒有任何字符串字面值可能會超過行的末尾 。老版本的GCC 接受多行字符串常量。 您可以使用續行代替, 或字符串常量毗連

已經給其他的答案既提供持續的線條和字符串連接的例子。

相關問題