---
title: "解决编译时出现的警告：format string is not a string literal (potentially insecure)┊"
author: "white__cat"
date: "2012-07-30T14:42:36Z"
tags: []
categories: ["移动开发"]
slug: "format-string-is-not-a-string-literal-potentially-insecure"
draft: false
lastmod: "2012-07-30T14:42:36Z"
id: 1612204
url: "https://white--cat.iteye.com/blog/1612204"
---

在Xcode 4.2（iOS 5）之前，我猜大家都和我一样很喜欢下面的调试输出写法：

[?](http://www.cocoachina.com/bbs/read.php?tid=87645)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

`NSString` `*str = @"Attention";`

`    ` 

`// first warning`

`NSLog(str);`

`    ` 

`// second warning`

`NSLog([str stringByAppendingFormat:@", %@", @"Xcode 4.2 do not support this format!"]);`

`    ` 

`// third warning`

`NSLog([NSString` `stringWithFormat:@"%@, Xcode 4.2 do not support this format!", @"Attention"]);`

`    ` 

`// fourth warning`

`NSException` `*exception = [NSException` `exceptionWithName:@"Attention"`

`reason:@"Xcode 4.2 do not support this format!"`

`userInfo:nil];`

`    ` 

`NSLog(exception);`

 

但是在Xcode 4.2(iOS 5)之后，貌似苹果更新的编译器，出了支持ARC的Apple LLVM compiler 3.0。然后我发现每次编译，以前的这些输出都会产生一个warning(警告，黄色三角形)。  
在StackOverflow和iPhone Dev SDK查找相关答案之后，发现在最新版的编译器里面NSLog为了安全，只接受格式化的字符串，因为NSLog底层也是用printf来格式化输出的。  
所以上面的写法都会给出警告，可以把上面的写法修改为以下合法模式：

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

`NSString` `*str = @"Attention";`

`    ` 

`// first warning`

`NSLog(str);                          // warning`

`NSLog(@"%@", str);         // solution`

`NSLog(str, nil);                   // solution`

`    ` 

`// second warning`

`NSLog([str stringByAppendingFormat:@", %@", @"Xcode 4.2 do not support this format!"]);                         // warning`

`NSLog(@"%@", [str stringByAppendingFormat:@", %@", @"Xcode 4.2 do not support this format!"]);         // solution`

`NSLog([str stringByAppendingFormat:@", %@", @"Xcode 4.2 do not support this format!"], nil);                   //solution`

`    ` 

`// third warning`

`NSLog([NSString` `stringWithFormat:@"%@, Xcode 4.2 do not support this format!", @"Attention"]);             // warning`

`NSLog(@"%@, Xcode 4.2 do not support this format!", @"Attention");                                                                // solution`

`NSLog([NSString` `stringWithFormat:@"%@, Xcode 4.2 do not support this format!", @"Attention"], nil);      // solution`

`    ` 

`// fourth warning`

`NSException` `*exception = [NSException` `exceptionWithName:@"Attention"`

`reason:@"Xcode 4.2 do not support this format!"`

`userInfo:nil];`

`    ` 

`NSLog(exception);                        // warning`

`NSLog(@"%@", exception);       // solution`