Kordan Ou
Kordan Ou

Reputation: 1682

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. And there is a warning that "AppDelegate may not respond to -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);
}

Upvotes: 0

Views: 940

Answers (2)

Markus
Markus

Reputation: 2572

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,

 - (void) initWithLength:(float)length;

to my class. NSMutableData already defines this method, and it uses an integer.

My method then produced garbage: the float value was passed as 0x0 no matter what I sent it...

Upvotes: 0

Cesar
Cesar

Reputation: 4437

You can easily resolve both your problems by adding the method prototype into the header file (<sameName>.h):

- (void)printFloat:(float)f;

Upvotes: 2

Related Questions