views:

40

answers:

2

I'm trying to get the integer value of an NSNumber initialized with a float and I was expecting that intValue handle the conversion (as the docs say).

#import <Foundation/Foundation.h>
#import "Fraction.h"
#import "Complex.h"
#import "ComplexMathOps.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


    NSNumber    *myNum, *floatNum, *intNum;

    intNum = [NSNumber numberWithInt:100];
    floatNum = [NSNumber numberWithFloat:99];

    myNum = [floatNum intValue];

    NSLog(@"%@",myNum);



    [pool drain];
    return 0;
}

What am I doing wrong? What's the correct way to convert between different numeric types?

+1  A: 

it works fine for me declaring it like this:

NSNumber * floatNum = [NSNumber numberWithFloat:99];
NSLog(@"%d",[floatNum intValue]);
JonLOo
For some reason I was expecting intValue to return a NSNumber wrapping the int and not the int. And that's were I got into trouble… O:-) Thanks!
Fernando
you are welcome :)
JonLOo
+4  A: 

[floatNum intValue] returns an int-type, but you declared myNum as NSNumber. Declare myNum as int and everything works as expected.

Goeran
Fernando: You should also be getting a warning from the compiler about this (something along the lines of “assignment converts integer to pointer without cast”). Don't ignore the warnings in the build results—the compiler is pointing at what you did wrong. Declaring `myNum` as the same type that `intValue` returns will both resolve the warning and fix the problem.
Peter Hosey