Jonathan Thurft
Jonathan Thurft

Reputation: 4173

NSNumber returning different value than the original int

I am quite new to objective-c and I am trying to convert an int into a NSNumber so that I can save it into Core-Data.

I've the following piece of code (index is an NSInteger)

- (void) associateOrNotToARoutine:(NSString*)exerciseName associate:(BOOL)associate index:(NSInteger)index

NSLog(@"number w index %d, %d",[NSNumber numberWithInteger:index],index);

and it returns

number w index 170413600, 2

I need an int of 2 to be translated into a number 2 along with all other numbers to be translated into the correct number... Could anyone tell me why i am getting this convertion? I tried reading on NSNumber manual but i found nothing

Upvotes: 2

Views: 1374

Answers (3)

user1040049
user1040049

Reputation:

Even though this question has already been answered, I thought I'd flesh out a longer answer for future readers in general:

What's happening?
%d is a C format string used to indicate one of the passed parameters is an integer (int) ivar value. Much like %f is used for float values.

[NSNumber numberWithInteger:index] returns a pointer to an NSNumber instance. If you use %d, NSLog thinks you're passing it an integer when, in fact, you're passing a pointer. So the pointer value (a memory address) is printed.

What's %@?
As mentioned by trojanfoe: %@ tells NSLog() that you are passing an object. In that case, NSLog asks the object to describe itself using a string… it calls the description method.

Specific answer
For this specific question, there are multiple ways. The two main one being:

  • NSLog(@"number w index %@, %d", [NSNumber numberWithInteger:index], index);
  • NSLog(@"number w index %d, %d", [[NSNumber numberWithInteger:index] intValue], index);

Extra goodness
When using %@, the passed object can be anything that responds to description, essentially any descendant of NSObject. Also, if you're creating your own classes, it's a good idea to overload description to return a more meaningful string than the default NSObject implementation.

// Try using it with NSArray or NSDictionary and see how each describe themselves.
NSLog(@"the array description: %@", myArray);
NSLog(@"the dictionary description: %@", myDictionary);

Upvotes: 4

trojanfoe
trojanfoe

Reputation: 122449

Try:

NSLog(@"number w index %@, %d",[NSNumber numberWithInteger:index],index);
                       ^^

The %@ format specifier will call the [NSNumber description] method, which should return the value you are after. Your original code will return the address of the NSNumber object, not its content.

Upvotes: 8

Ravi Vooda
Ravi Vooda

Reputation: 5256

You should use,

[[NSNumber numberWithInteger:index] intValue] 

to get the integer value, the NSNumber, is holding

Upvotes: 2

Related Questions