PDA

View Full Version : variables won't print in console




i-ash
Feb 19, 2009, 05:43 PM
Hi All,

I am just starting out in Objective-C programming, following the Kochan book "Programming in Objective-C 2.0".

I'm sure this has a simple answer... :o

The following code has me scratching my head - I cannot see why the variables X & Y don't get printed to the screen in the console window.

Can some please assist me?

Any help much appreciated!

Thanks

// Class called XYPoint that will hold a Cartesian coordinate (x,y), where x and y are integers.

#import <Foundation/Foundation.h>

// ---- @interface section ----

@interface XYPoint : NSObject
{
int xCoord;
int yCoord;
}

- (void) setX: (int) x;
- (void) setY: (int) y;
- (int) getX;
- (int) getY;

@end

// ---- @implementation section ----

@implementation XYPoint

- (void) setX: (int) x
{
xCoord = x;
}

- (void) setY: (int) y
{
yCoord = y;
}

- (int) getX
{
return xCoord;
}

- (int) getY
{
return yCoord;
}

@end


int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

XYPoint *myXYPoint = [[XYPoint alloc] init];

// Set X Y points

[myXYPoint setX: 7];
[myXYPoint setY: 42];

// Display the X Y points

NSLog (@"The value of the x point is: ", [myXYPoint getX]);
NSLog (@"The value of the y point is: ", [myXYPoint getY]);

[myXYPoint release];

[pool drain];
return 0;
}

End result:

[Session started at 2009-02-20 10:22:20 +1100.]
2009-02-20 10:22:21.017 ch3ex7[97725:10b] The value of the x point is:
2009-02-20 10:22:21.018 ch3ex7[97725:10b] The value of the y point is:

The Debugger has exited with status 0.



lee1210
Feb 19, 2009, 05:53 PM
NSLog uses some C magic to support a variable number of parameters. The details of this are, i'm sure, not too interesting to you at this point, so i'll omit them. The crux, though, is that you need to include in your format string a format specifier that tells NSLog what sorts of things you will pass in afterwards, and where to print them. So if you change:

NSLog (@"The value of the x point is: ", [myXYPoint getX]);
NSLog (@"The value of the y point is: ", [myXYPoint getY]);

to

NSLog (@"The value of the x point is: %d", [myXYPoint getX]);
NSLog (@"The value of the y point is: %d", [myXYPoint getY]);


Indicating that you will also be passing a single integer to be printed (%i works as well, just used to %d), all should work as expected.

-Lee

i-ash
Feb 19, 2009, 06:09 PM
Cheers thanks Lee, I knew it would be something simple. :rolleyes: