【发布时间】:2013-02-06 02:51:39
【问题描述】:
为示例代码的 Objective-C 特性道歉,但我很确定我的问题的答案在 C 标准库和/或 Apple clang 编译器中。
我有一个NSArray,其中包含可变数量的项目。我想使用项目计数来创建一个介于 1 和 3 之间的值。我正在使用 C MAX 宏,但它有一些奇怪的行为:
NSLog( @"%d %d %d %d", 1, [tasks count], 3 - [tasks count], MAX( 1, 3 - [tasks count] ) );
当增加tasks 中的项目数时,此日志语句的输出是这样的:
1 0 3 3
1 1 2 2
1 2 1 1
1 3 0 1
1 4 -1 -1
我稍微研究了一下文档,发现count 函数返回了NSUInteger。我的困境的解决方案只是将返回值类型转换为NSInteger:
NSLog( @"%d %d %d %d", 1, (NSInteger)[tasks count], 3 - (NSInteger)[tasks count], MAX( 1, 3 - (NSInteger)[tasks count] ) );
1 0 3 3
1 1 2 2
1 2 1 1
1 3 0 1
1 4 -1 1
(如果你不熟悉 Objective-C,在 32 位架构上,NSInteger 的类型定义为 int,NSUInteger 是 unsigned int。)
我很难理解在我的原始代码中隐式发生的类型转换,这导致了我不直观的结果。有人能点亮吗?
【问题讨论】: