Edmund Ching
Edmund Ching

Reputation: 69

Outputting Formatted NSString

UIAlertView *message = [[UIAlertView alloc] initWithTitle:[[LanguageManager sharedLanguageManager] get:@"Notice"]
                                                  message:[NSString stringWithFormat:[[LanguageManager sharedLanguageManager] get:@"Notice_Text"]]
                                                 delegate:nil
                                        cancelButtonTitle:[[LanguageManager sharedLanguageManager] get:@"Close"]
                                        otherButtonTitles:nil];

Hi, let me explain my codes above. Basically it calls up an UIAlertView with data read from a .plist via my LanguageManager singleton class. The LanguageManager get function basically returns a NSString*. I know I should use the NSLocalizedString class but I had been using this class for a while now, so I had decided to stick to it.

My problem lies with the "message:" parameter. The string I am trying to read contains formatting characters like \n but it does not output correctly and appears as \n instead of a line break when printed. I also get the "Format string is not a string literal" warning. Other parts of the app using similar method to return a string which contains %d or %f works correctly though, just the '\n' character not working.

Does anyone have any idea how I may overcome this?

Upvotes: 0

Views: 183

Answers (1)

Christian Stieber
Christian Stieber

Reputation: 12496

"\n" is not a "formatting character": the compiler translates it to the appropiate code; the string NEVER contains the "\" and "n" characters.

Thus, if you string comes from a source that is NOT compiled by a (Objective-)C(++) compiler, "\n" will be just the two characters. Nothing will turn them into a newline, unless you do it yourself with something like

NewString=[MyString stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];

Note the two different strings: in the first case, "\" prevents the compiler from doing the \n -> newline conversion, while the second string will be an actual newline.

The warning about a non-literal format string is somewhat pointless; I've yet to find a good way to get rid of that one (for now, I just disable it entirely, using -Wno-format-nonliteral on clang++ >= 4.0).

Upvotes: 1

Related Questions