NSUInteger到int

the*_*epp 2 cocoa printf nsuinteger

我写了一个使用myarray的方法,在同一个类中定义.当我使用count时它总是返回0.当我使用:

printf("%d", [myarray count]);
Run Code Online (Sandbox Code Playgroud)

编译说:

Format '%d' expetcs type 'int', but argument 2 has type 'NSUInteger'
Run Code Online (Sandbox Code Playgroud)

为什么?

das*_*ght 5

你应该使用%lu而不是%d.编译器会根据您传递给的参数检查格式字符串printf,看到您传递的是unsigned但是将其作为有符号整数打印,并发出警告.警告表明printf,当数据类型意味着不同的语义,即大的正整数时,对于大于或等于2 ^ 31的数字将输出大的负数.

编辑回应Josh Caswell和thepepp的评论

  • [docs say](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW5)使用`% lu`为`NSUInteger`. (3认同)
  • 你不仅应该使用`%lu`,还应该将你的`NSUInteger`转换成`(unsigned long)`.通常你会发现省略强制转换是正常的,但是为了严格正确,你应该拥有它,以及[String Format specifiers](http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings /Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1)指南告诉您执行演员表. (2认同)