objective-c 如何将 id 转换为浮点数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/307128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:55:19  来源:igfitidea点击:

How do I cast id to a float?

objective-cmacoscasting

提问by e.James

I'm having trouble with this code:

我在使用此代码时遇到问题:

NSRect itemFrame;
id item;
// code to assign item goes here.
itemFrame.origin.y -= [item respondsToSelector:@selector(selectedHeight)] ? [item selectedHeight]   : [self defaultSelectedHeight];

This is the problematic bit:

这是有问题的一点:

[item selectedHeight]

The compiler is assuming that the return type is id. I though that adding a cast would fix this:

编译器假设返回类型是 id。我认为添加演员表可以解决这个问题:

(float)[item selectedHeight]

but it doesn't work.

但它不起作用。

What am I doing wrong? (I suspect the problem is to do with resolving pointers related to id but I can't find any relevant documentation).

我究竟做错了什么?(我怀疑问题与解决与 id 相关的指针有关,但我找不到任何相关文档)。

回答by e.James

you want [[item selectedHeight] floatValue], assuming that the selectedHeight returns an NSNumber.

你想要[[item selectedHeight] floatValue],假设 selectedHeight 返回一个NSNumber.

回答by csonuryilmaz

I know that below code works for iOS 6 SDK. I assume that objobject contains a float value.

我知道下面的代码适用于 iOS 6 SDK。我假设obj对象包含一个浮点值。

id obj;
float fVal;

fVal = [obj floatValue];

回答by Marc Charbonneau

You need to look at the declaration of your selectedHeightmethod. The problem is either that the method is returning a pointer to an object (id), or you haven't imported the header file for itemin the file that contains the code snippet, so Xcode assumes it's a pointer by default.

您需要查看selectedHeight方法的声明。问题是该方法返回了一个指向对象 (id) 的指针,或者您没有item在包含代码片段的文件中导入头文件,因此 Xcode 默认假定它是一个指针。

You can't cast a pointer to a float, since they're fundamentally incompatible types. Once you get your declarations straightened out though you should be okay.

您不能将指针强制转换为浮点数,因为它们从根本上是不兼容的类型。一旦你理顺了你的声明,虽然你应该没问题。

回答by Sherm Pendley

The compiler makes that kind of assumptions when multiple classes declare methods with the same name, that return different types. Since your "item" variable is typed as an "id," the compiler doesn't know which of these classes it will be sending the message to at run time, and chooses one.

当多个类声明具有相同名称的方法时,编译器会做出这种假设,这些方法返回不同的类型。由于您的“item”变量被输入为“id”,编译器不知道它将在运行时将消息发送到这些类中的哪一个,并选择一个。

To avoid this problem, you can inform the compiler what class "item" is an instance of, by declaring it with a specific type instead of the generic "id":

为了避免这个问题,您可以通过使用特定类型而不是通用“id”声明它来通知编译器“item”是哪个类的实例:

SomeItemClass *item;

You could also avoid it by not declaring identically-named methods that return different types.

您也可以通过不声明返回不同类型的同名方法来避免它。