Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: Format string is not a string literal [duplicate]

I am getting "Format string is not string literal" warning from following line

NSString *formattedString = [[NSString alloc] initWithFormat:format arguments:valist];

I using this in following function

- (void)logMessage:(NSString *)format
         level:(LoggingLevel)level
withParameters:(va_list)valist {
         if (level >= self.loggingLevel) {
              NSString *formattedString = [[NSString alloc] initWithFormat:format arguments:valist];        
         } 

Any idea how to fix this ? I am using Xcode 4.6.3

like image 849
AAV Avatar asked Nov 30 '22 03:11

AAV


2 Answers

Suppress it using:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-nonliteral"

- (void)logMessage:(NSString *)format
         level:(LoggingLevel)level
withParameters:(va_list)valist {
         if (level >= self.loggingLevel) {
              NSString *formattedString = [[NSString alloc] initWithFormat:format arguments:valist];        
         } 

#pragma clang diagnostic pop
like image 98
trojanfoe Avatar answered Dec 02 '22 18:12

trojanfoe


If you tell the compiler that your method has a format-like argument, using the NS_FORMAT_FUNCTION macro:

- (void)logMessage:(NSString *)format
         level:(LoggingLevel)level
withParameters:(va_list)valist NS_FORMAT_FUNCTION(1,0) {
         if (level >= self.loggingLevel) {
              NSString *formattedString = [[NSString alloc] initWithFormat:format arguments:valist];        
         } 
}

then

  • the compiler warning in your method goes away, but
  • you get a warning if you call your method with a format string which is not a string literal.

Example:

NSString *abc = @"foo %@ bar";
[self logMessage:abc level:7 withParameters:NULL];

warning: format string is not a string literal [-Wformat-nonliteral]
[self logMessage:abc level:7 withParameters:NULL];
                 ^~~

ADDED: The same applies to the functions mentioned in your comments. They should also be "tagged" with NS_FORMAT_FUNCTION:

+ (void)logVeryFineWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2)
{
    va_list ap;
    va_start(ap, format);
    [[self sharedInstance] logMessage:format level:VERY_FINE withParameters:ap];
    va_end(ap);
}

+ (void)say:(NSString *)formatstring, ... NS_FORMAT_FUNCTION(1,2)
{
    va_list arglist;
    va_start(arglist, formatstring);
    // This is not needed: 
    // NSString *litralString = [NSString stringWithFormat:@"%@",formatstring];
    NSString *statement = [[NSString alloc] initWithFormat:formatstring arguments:arglist];
    va_end(arglist);
    [ModalAlert ask:statement withCancel:@"Okay" withButtons:nil];
}
like image 26
Martin R Avatar answered Dec 02 '22 16:12

Martin R