Dan
Dan

Reputation: 1697

How to split a string in Objective-C without breaking the code

Xcode throws all sorts of errors when I insert a line break into a string. E.g., this fails:

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

But this works:

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

I'd prefer the former because it's cleaner to look at (shorter lines), but the code breaks. What's the best way to deal with this? (Subquestion: is this referenced in any of the syntax guides? I searched all my books for "line break" to no effect.)

Upvotes: 4

Views: 1560

Answers (3)

sbooth
sbooth

Reputation: 16966

String literals in C may not contain newlines. To quote http://gcc.gnu.org/onlinedocs/cpp/Tokenization.html:

No string literal may extend past the end of a line. Older versions of GCC accepted multi-line string constants. You may use continued lines instead, or string constant concatenation

The other answers already given give examples of both continued lines and string concatenation.

Upvotes: 2

Julio Gorgé
Julio Gorgé

Reputation: 10106

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

Upvotes: 8

Scott
Scott

Reputation: 17037

All these should work:

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);

Upvotes: 8

Related Questions