Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Incompatible pointer to integer conversion initializing 'int' with an expression of type 'NSNumber *'"

I suspect this is something really simple, but I'm trying to get an int that I have stored in a dictionary and the line I'm using is this..

 int mapX = [NSNumber numberWithInt:[templateObject valueForKey:@"mapX"]];

But it's giving me the error...

Incompatible pointer to integer conversion sending 'id' to parameter of type 'int'

and

Incompatible pointer to integer conversion initializing 'int' with an expression of type 'NSNumber *';

If I try...

NSNumber *mapX = [NSNumber numberWithInt:[templateObject valueForKey:@"mapX"]];

I basically get the same error. I know I'm probably just using the wrong syntax, but I'm not sure how else to write it.

Thanks for any help.

like image 216
Phil Avatar asked Nov 05 '12 18:11

Phil


2 Answers

A couple of points:

  • [NSNumber numberWithInt:[templateObject valueForKey:@"mapX"]];

    Returns an NSNumber*, which you're trying to store in an int.

  • NSNumber* mapX = [NSNumber numberWithInt:[templateObject valueForKey:@"mapX"]];

    won't work either, because [templateObject valueForKey:@"mapX"] isn't an int. You can only store objects in NSDictionary, not primitive types.

You might want to try (Assuming I have the types correct)

NSNumber* mapXNum = [templateObject valueForKey:@"mapX"];
int mapX = [mapXNum intValue];
like image 76
WDUK Avatar answered Sep 24 '22 03:09

WDUK


 int mapX = (int)[[templateObject valueForKey:@"mapX"] integerValue];

the above solution is assuming the templateObject valueForKey:@"mapX" returns an NSNumber. If it doesn't and you want to convert it to an NSNumber, use this solution instead:

 int mapX = (int)[(NSNumber *)[templateObject valueForKey:@"mapX"] integerValue];

Typecasting in ObjC is the.worst.

like image 33
jungledev Avatar answered Sep 24 '22 03:09

jungledev