Page 1 of 1

Making classes in Objective-C

Posted: Thu Apr 01, 2010 2:57 pm
by ajtgarber
I've been playing around with Objective-C for a little while now, but I still can't figure out what is wrong with this, the class is supposed to store an integer (named b).
And it is supposed to print that variable to the console when you call the toConsole method, but when I run it, the output seems to spit out random letters

Code: Select all

#import <Foundation/Foundation.h>
@interface Badger : NSObject {
	int b;
}
//constructor
-(Badger*) setB: (int)a;
//prints b to the console
-(void) toConsole;
@end

@implementation Badger
//constructor
-(Badger*) setB: (int)a {
        //initialize the superclass (which is NSObject)
	self = [super init];
        //if the initialization succeeded
	if(self) {
                //set b
		b = a;
                //return the new instance
		return self;
	}
        //else return nil
	return nil;
}
//print b to the console
-(void) toConsole {
        //call the c function printf
	printf(""+b);
}
@end

//Main method
int main(int argc, char *argv[])
{
        //create a new Badger named philip
	Badger *philip = [[Badger alloc] setB: 12];
        //make philip print his variable to the console
	[philip toConsole];
	[philip release];
	return 0;
}
For output I've gotten:
The Debugger Debugger is attaching to process
[Session started at 2010-04-01 15:45:12 -0400.]
oc
The Debugger has exited with status 0.
[Session started at 2010-04-01 15:45:28 -0400.]
dger
The Debugger has exited with status 0.
[Session started at 2010-04-01 15:45:50 -0400.]
ect
The Debugger has exited with status 0.
[Session started at 2010-04-01 15:46:26 -0400.]
ect
The Debugger has exited with status 0.
[Session started at 2010-04-01 15:46:46 -0400.]
ect
The Debugger has exited with status 0.
Any help would be appreciated

Re: Making classes in Objective-C

Posted: Thu Apr 01, 2010 4:50 pm
by M_D_K
yeah you're supposed have printf like this

Code: Select all

printf("%d\n", b);
what you're doing is pointer arithmetic on a constant string (which is empty) so printf is printing some random memory.

EDIT: here is info on printf