如果你告诉编译器你的方法有一个类似格式的参数,使用
NS_FORMAT_FUNCTION
宏:
- (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];
}
}
然后
- 您方法中的编译器警告消失了,但是
- 如果您使用不是字符串文字的格式字符串调用方法,则会收到警告。
例子:
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];
^~~
补充:这同样适用于您评论中提到的功能。它们也应该被“标记” 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];
}