Reputation: 1224
What is the highest int that NSNumber allows? I've seen the answer elsewhere on these forums hence why I'm deeply confused here.
int miles = 35000;
vehicle.mileage = [NSNumber numberWithInt:miles];
NSLog(@"int value = %d", miles);
NSLog(@"mileage = %@", vehicle.mileage);
The output is:
int value = 35000
mileage = -30536
I must be missing some terrible easy here, but can someone explain to me why this is not working correctly?
UPDATE: After looking further, vehicle.mileage is getting set correctly to 35000 but when I display this via NSLog(@"%@", vehicle.mileage) it is outputting it incorrectly. I have yet to find the "magic" value when this stops working because as of now, it works for values up to ~30,000.
Upvotes: 1
Views: 2542
Reputation: 9091
Overview
NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char, short int, int, long int, long long int, float, or double or as a BOOL. (Note that number objects do not necessarily preserve the type they are created with.) It also defines a compare: method to determine the ordering of two NSNumber objects.
So NSNumber
is as big as what it wraps. For your unexpected result you can check comment bellow your qestion from @sjs.
Upvotes: 1
Reputation: 9157
The limit NSNumber
integer can have is known as INT_MAX
but 35, 000 is nowhere close to that. The problem must be with vehicle
object or the mileage
property in the vehicle
, either of them may be nil
So, go ahead and log with this conditional statement:
if (!vehicle) {
NSLog(@"Vehicle is nil");
}
else if (!vehicle.mileage) {
NSLog(@"Vehicle's mileage is nil");
}
Tell me your result
Upvotes: 0
Reputation: 9093
+numberWithInt:
interprets the value as signed int. Mileage would never be negative, so I suggest using [NSNumber numberWithUnsignedInt:]
Upvotes: 0
Reputation: 21966
NSNumber is just a wrapper so it goes in overflow when the wrapped primitive type goes in overflow.
So if you use numberWithInt the maximum number allowed is INT_MAX (defined in limits.h), if you use a numberWithFloat the maximum number allowed is FLOAT_MAX, and so on.
So in this case you aren't going in overflow, I doubt that INT_MAX would be so low.
Upvotes: 3