简体   繁体   English

如何在Objective-C中按值传递浮点数?

[英]How could I pass the float number by value in Objective-C?

In the following code, I passed the "1.3f" to printFloat, but it was the wrong value (in this case, -2.000000) after was "f" received. 在下面的代码中,我将“ 1.3f”传递给printFloat,但是在收到“ f”之后它是错误的值(在这种情况下为-2.000000)。 And there is a warning that "AppDelegate may not respond to -printFloat:" 并且有一条警告,“ AppDelegate可能不响应-printFloat:”

Where did I get it wrong? 我在哪里弄错了?

- (void)applicationDidFinishLaunching:(UIApplication *)application{
    // Override point for customization after application launch
    [window makeKeyAndVisible];
    [self printFloat:1.3f];
}

- (void)printFloat:(float)f {
    NSLog(@"%f",f);
}

通过将方法原型添加到头文件( <sameName>.h )中,可以轻松解决两个问题:

- (void)printFloat:(float)f;

If you include the correct definition in the class' header file, and you still cannot pass floats by reference, make sure you're not overriding an existing method of a parent class... 如果您在类的头文件中包含正确的定义,并且仍然不能通过引用传递浮点数,请确保您没有覆盖父类的现有方法...

For example, I had this problem because my class was derived from NSMutableData (which I did not know then), and I added a method, 例如,我遇到了这个问题,因为我的类是从NSMutableData派生的(当时我还不知道),然后添加了一个方法,

 - (void) initWithLength:(float)length;

to my class. 上我的课。 NSMutableData already defines this method, and it uses an integer. NSMutableData已经定义了此方法,并且使用整数。

My method then produced garbage: the float value was passed as 0x0 no matter what I sent it... 然后我的方法产生了垃圾:无论我发送了什么,float值都被传递为0x0 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM