Fogmeister
Fogmeister

Reputation: 77651

iOS passing in an output float parameter to a function

I'm trying to create a function to calculate the mean, max, min and standard deviation of a set of numbers.

I'd like it to work like the UIColor function - (void)getRed:green:blue:alpha. i.e. you pass in the four float values and the function then overwrites them.

I'm struggling to find the right syntax for it.

My function is...

- (void)calculateStatsAverage:(float)average
            standardDeviation:(float)standardDeviation
                      minimum:(float)minimum
                      maximum:(float)maximum
{
    //pseudo code
    average = total / count;
    minimum = min value;
    etc...
    //
}

The problem I'm getting is getting the values out again.

If I change the function to use float* (which is what the UIColor function does) then my calculations don't like assigning the variables.

To simplify...

Imagine these functions. The first is called from elsewhere.

- (void)runThisFunction
{
    float someOutputValue = 0.0;

    [self changeTheValue:someOutputValue];

    NSLog(@"The value is %f", someOutputValue);
}

- (void)changeTheValue:(float)value
{
    value = 10.0;
}

I'd like this code to output "The value is 10.0"; But at the moment I'm getting "The value is 0.0".

Please could you show me how to write these two functions. From there I'll be able to work out the rest.

Thanks

Upvotes: 0

Views: 832

Answers (2)

Snips
Snips

Reputation: 6773

Your NSLog is displaying the value of the local variable 'someOutputValue', which has been assigned to be 0.0.

Your 'changeTheValue' method has no effect.

The following code may help,

- (void)runThisFunction
{
    float someOutputValue = 0.0;

    float resultOfCalc = [self calcTheValue:someOutputValue];

    NSLog(@"The value is %f", resultOfCalc);
}

- (float) changeTheValue:(float)value // note that this method returns a float
{
    float newValue;

    // do whatever calc is appropriate, e.g.

    newValue = value + 10.0;

    return newValue;  // pass back the result of calc
}

This will output,

The value is 10.

Upvotes: 0

Carl Veazey
Carl Veazey

Reputation: 18363

- (void)passByRefMethod:(float *)ptr
{
    *ptr = MYVALUE;
}

Sorry for formatting, typed on phone. Hope this helps!

This technique is often called pass by reference, and it's part of C so you can use that to search for more info.

Upvotes: 2

Related Questions