【问题标题】:One off errors with NSLog and NSString stringWithFormatNSLog 和 NSString stringWithFormat 的一次性错误
【发布时间】:2010-05-06 01:55:55
【问题描述】:

有谁知道为什么 NSLog 和 NSString 会出现一次性错误?它在我的程序的 99% 中运行良好,但由于某种原因,此错误出现在我的模型的描述方法之一中:

Example code:
localFileId = 7;
type = 2;
localId = 5;
NSLog(@"CachedFile localId=%d, 2=%d, localFileId=%d, type=%d, path=%@", localId, 2, localFileId, type, self.path);

Example Result: 
CachedFile localId=5, 2=0, localFileId=2, type=7, path=(null)

注意插入其中的“0”,它应该是“2=2”。 NSString stringWithFormat 也会发生这种情况。

【问题讨论】:

标签: iphone objective-c cocoa-touch


【解决方案1】:

%d 需要一个 int 或 long 参数,即堆栈上的 4 个字节。

您没有显示 localId 的声明,它的大小是否正确?如果 %d 告诉 NSLog 读取 4 个字节时是 2 个字节,那意味着 NSLog 也读取了下一个参数的前 2 个字节,然后那个被关闭了 2 个字节,等等。

编辑:好的,那是错误的,我刚刚尝试过。我实际上把它倒过来了,而不是 localId 太短( 4 个字节),请参阅下面的@dreamlax 的 cmets。

short shortX = 1;
int intX = 2;
NSLog(@"shortX = %d, intX = %d", shortX, intX);

打印:shortX = 1, intX = 2

【讨论】:

  • 不,每个整数类型在作为参数传递给可变参数函数时都会受到整数提升。
  • 问题是localId 的类型是否超过int,如果它是long long intlong int
  • 是的,长整数是问题所在。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多