Objective-C 中类型之间的转换
作为一名刚入门的 Objective-C 开发人员,我没有耐心实际进行一些研究,而不仅仅是深入研究,我遇到了以下问题:
我有一个 CGFloat,我想将它除以某个值,然后使用结果作为 NSInteger。
示例:
CGPoint p = scrollView.contentOffset; //where p is a CGFloat by nature
NSInteger * myIndex = p.x/468.0;
编译时,出现错误:“初始化中的类型不兼容”。 我猜这是因为 CGFloat 和 NSInteger 之间不匹配。
我应该知道什么才能摆脱这个困境? 对不起,打扰你。
Being a starting Objective-C developer, and not having the patience to actually do some studying, rather than just diving into things, I ran into the following:
I have a CGFloat, and I want to divide it by something, and use the result as an NSInteger.
Example:
CGPoint p = scrollView.contentOffset; //where p is a CGFloat by nature
NSInteger * myIndex = p.x/468.0;
While compiling, I get the error: "Incompatible types in initialization".
I guess that's because of the mismatch between the CGFloat and the NSInteger.
What should I know to get out of this? Sorry for bothering you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两个问题。 您正在使用 NSInteger 指针 (NSInteger *myIndex)。 并且您需要进行强制转换才能从 float 变为 int。 就像这样:
Two problems. You're using a NSInteger pointer (NSInteger *myIndex). And you'll need a cast to go from float to int. Like so:
NSInteger 不是实际的对象类型。 它是原始整数类型的 typedef。 删除*,您的示例应该可以工作。 现在,您尝试将数学结果分配为指针,并且收到该错误消息。
NSInteger is not an actual object type. It is a typedef for a primitive integer type. Remove the * and your example should work. As it is now, you're trying to assign the result of your math as a pointer and you're getting that error message.