tags:

views:

1529

answers:

2

Hi Everyone:

I have a NSSlider that is attempting to convert a regular float into a CGFloat. The code that I am using:

CGFloat testing = [mainSlider floatValue];

However this simply makes the testing variable "0.00" when I attempt to log it.

NSLog(@"%f", testing);

Does anyone have any ideas as to why this would happen? Thanks for any help.

+1  A: 
  1. check that mainSlider isn't nil
  2. try this just in case (can't remember if CGFloat is a double or not):

    NSLog(@"%f", (double)testing);

  3. Check that the variable isn't being shadowed like this:

    CGFloat testing = 0.0;
    if(YES){
        CGFloat testing = [mainSlider floatValue];
        //should be: testing = [mainSlider floatValue];
    }
    NSLog(@"testing = %f", testing); //this will print "testing = 0.000000"
    
Tom Dalling
Note that casting to `double` will not restore any precision lost when `floatValue` converted the value to single-precision. Better to just use `doubleValue`.
Peter Hosey
Also, the cast to (double) is unnecessary. The c language does that implicitly when calling a vargs function with a float argument.
Jon Hess
mainSlider isn't nil, just for some weird reason it doesn't transfer into a CGFloat. When I log it like: NSLog(@"%f", [mainSlider floatValue]), it returns the result. But not when I create a CGFloat from it.
PF1
Another wrinkle in the whole `double` casting debate is `CGFloat` is `typedef`ed to `float` when running in 32-bit mode, but `double` when running in 64-bit mode. So, in 32-bit mode, `CGFloat testing = [mainSlider doubleValue];` squashes it in to a single-precision `float` type anyways...
johne
Okay, this problem is just getting stranger and stranger. The same code (the same exact code) runs in every other function EXCEPT the one that I try to get it to run in. For some reason drawRect:(NSRect)rect just doesn't seem to like that code...
PF1
In that case, it could be shadow variables. Check to see if there are any other variables named "testing" in drawRect.
Tom Dalling
@Tom Dalling It logs testing = 0.000000, does that mean that there is another variable called testing?
PF1
Possibly, but not definitely.
Tom Dalling
Even when I set the other function to be called from drawRect, it still outputs 0 for the slider value. I am using the following code to call the function: [self changeItem:self]; Does anyone know why this would be caused? The IBAction is usually called by a NSSlider, which may be the problem.
PF1
A: 

I don't have enough rep to comment, but what's your expected value? Have you moved the slider and expecting a different result?

Ben Clark-Robinson
Mozketo: Yes, I have moved the slider and when I log the actual result (NSLog(@"%f", [mainSlider floatValue])) it works just fine.
PF1