因此,在使用 NSString
的 -sizeWithFont
系列方法调用时,我似乎遇到了一些奇怪的行为,具体取决于我是否在 iPhone 模拟器上调用它或实际设备。
很简单,当 -sizeWithFont:constrainedToSize:lineBreakMode:
方法调用的接收者为 nil
时,生成的 CGSize
会传回模拟器是 {0, 0}
。 但是,在设备上,返回结果与我在方法调用中指定为 constrainedToSize:
参数的 CGSize
值相同。请参阅以下日志语句:
模拟器:
someString: (null)
someStringSize: {0, 0}
设备:
someString: (null)
someStringSize: {185, 3.40282e+38}
模拟器上的行为正是我所期望的。并不是说这个问题很难规避,而是 1) 我有点困惑为什么这一系列函数在模拟器和实际设备上的行为不同,2) 为什么在 nil 上调用方法code> 接收者返回一个特定的、确定性的结果?
感谢你们提供的任何指示或见解!
编辑:我想我应该提到我正在针对 3.1 SDK 进行构建。
最佳答案
Apple 关于 Sending messages to nil 的文档有点解释了这一点:
The value returned from a message to nil may also be valid:
- If the method returns an object, then a message sent to nil returns 0 (nil) ...
- If the method returns any pointer type, any integer scalar of size less than or equal to sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0.
- If the method returns a struct, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, then a message sent to nil returns 0.0 for every field in the data structure. Other struct data types will not be filled with zeros.
- If the method returns anything other than the aforementioned value types the return value of a message sent to nil is undefined.
尽管本文档没有具体讨论 iPhone(并且是在 iPhone SDK 发布之前编写的),但请注意第三点和第四点:如果该方法返回一个结构体(例如 CGSize
),该行为依赖于平台。只有 CPU 寄存器中返回的值才会用零填充。我不是 iPhone ARM 架构方面的专家,但很可能在 iPhone 上,sizeWithFont:
的返回值不是在寄存器中返回的,这与 i386 不同。在这种情况下,在模拟器上运行时,返回的结构体将被填充零,而在 iPhone 上运行时,该值将是未定义的。
关于iphone - -sizeWithFont 在设备上的功能不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2632478/