When I run this code, the output is some 1084848 to the console. I can’t figure out why such odd output… here is the code.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *array = [[NSMutableArray alloc] init];
int someNumber = 3;
[array addObject:[NSNumber numberWithInt:someNumber]];
NSLog(@"%i" , [array objectAtIndex:0]);
[pool drain];
return 0;
}
Here’s the pseudocode of your program:
You are logging the first object in the array, but
NSArraycannot hold a primitive that’s not wrapped in an Objective-C object.To better understand your code, try changing these lines of code:
Expand them a little. Try this:
So, you’ve correctly wrapped the
intin anNSNumber, but you’re not unwrapping it. You need to ask yourNSNumberfor theintthat it holds like so:Or, to do the logging in one line:
The characters “
%i” is called a “formatter”. Different kinds of values require different formatters. When you are using an Objective-C object, you use “%@“. For anNSIntegerorint, you’d use%i. For a float, you’d use “%f“. The point is that you need to either unwrap that number, or use the Objective-C formatter for strings.A quick note about that weird value you were getting earlier: That’s a memory address in RAM. It’s the closest thing you’re going to get when you use an incorrect formatter. In some cases, using the wrong formatter will cause an EXC_BAD_ACCESS. You were “lucky” and got a weird value instead of a dead program. I suggest learning about strings and formatters before you move on. It will make your life a lot easier.