开发者

Xcode Gives Strange Output From NSArray

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]]; 
   NSL开发者_开发问答og(@"%i" , [array objectAtIndex:0]);
   [pool drain];
   return 0;
 }


the "%i" format specifier expects an integer, not an Object.

Try NSLog(@"%i" , [[array objectAtIndex:0] intValue]);

XCode is probably giving you a warning on this line: something like "Conversion specifies type 'int', but argument has type 'id'".


Here's the pseudocode of your program:

//
//  Inside of your main function....
//
//  Set up the Autorelease pool and then create an array
//
//  Declare an int  
//
//  Add the int to an array, while wrapping it in an NSNumber
//
//  Log the value of the first object in the array, using the int formatter
//
// Clean up and return
//

You are logging the first object in the array, but NSArray cannot hold a primitive that's not wrapped in an Objective-C object.

To better understand your code, try changing these lines of code:

int someNumber = 3; 
[array addObject:[NSNumber numberWithInt:someNumber]];

Expand them a little. Try this:

int someNumber = 3; 
NSNumber *aNumber = [NSNumber numberWithInt:someNumber];
[array addObject:aNumber];

So, you've correctly wrapped the int in an NSNumber, but you're not unwrapping it. You need to ask your NSNumber for the int that it holds like so:

[[array objectAtIndex:0] intValue];

Or, to do the logging in one line:

NSLog(@"%i" , [[array objectAtIndex:0] intValue]);

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 an NSInteger or int, 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.


When you use %i for integer values then you should give arguments as integer as below

NSLog(@"%i" , [[array objectAtIndex:0] intValue]);

But when you want object to be displayed then you must use %@ which identifies object in general case as below:

NSLog(@"%@", array);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜