Making classes in Objective-C

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
ajtgarber
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 97
Joined: Wed Jun 10, 2009 8:56 am

Making classes in Objective-C

Post 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
User avatar
M_D_K
Chaos Rift Demigod
Chaos Rift Demigod
Posts: 1087
Joined: Tue Oct 28, 2008 10:33 am
Favorite Gaming Platforms: PC
Programming Language of Choice: C/++
Location: UK

Re: Making classes in Objective-C

Post 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
Gyro Sheen wrote:you pour their inventory onto my life
IRC wrote: <sparda> The routine had a stack overflow, sorry.
<sparda> Apparently the stack was full of shit.
Post Reply