Reputation: 1430
I have an array with two elements which are 50 and 60:
NSArray*array = [NSArray arrayWithObjects:
[NSNumber numberWithLong:50],
[NSNumber numberWithLong:60], nil];
when using the array later on (in fact I´m writing this array as a default list to a plist file) I do it this way:
long value = [array objectAtIndex:1];
After this value contains 15559 what I don´t understand. In the debugger [array objectAtIndex:1] clearly shows (long)60.
I´m sorry, I don´t see what´s wrong ;(
Any ideas?
Ronald
Upvotes: 1
Views: 534
Reputation: 535547
A long
is not an NSNumber
. If you want to set value
as a long
to [array objectAtIndex:1]
you must convert it from an NSNumber to a long. You may wish to call longValue
on the NSNumber to do that.
You may be wondering why the compiler doesn't complain and help you here. It's probably because an object in an array is fetched as an id, and so most bets are off. This is a common problem with arrays: knowing what you're fetching, and what to do with it, is up to you.
Your screen shot of the debugger is excellent. Notice that if you look at it carefully now, with your head clear, it is very clear about the difference between value
which is a long
, on the one hand, and array[0]
which is an NSNumber wrapping a long, on the other. So the debugger was in fact answering your questions all along!
Upvotes: 6
Reputation: 726809
This is because you are not calling longValue
on the object that you get from the array:
long value = [[array objectAtIndex:1] longValue];
What your code gets is an address of NSValue
, which gets converted to a "junk" long
value unrelated to the number that you stored in the array.
Upvotes: 2