Reputation: 1
I am new to objective c and I wanted to practice by making a simple program. For some reason the method print will not operate. Any ideas?
#import <Foundation/Foundation.h>
@interface person: NSObject
{
//----Variables----
int age;
}
//----Methods----
-(void) print;
-(void)setAge: (int) a;
@end
@implementation person
-(void) print{
NSLog(@"You are %i years old!", age);
}
-(void) setAge: (int) a{
age=a;
}
@end
int main(int argc, char *argv[]){
@autoreleasepool{
person *alex; alex = [person alloc];
[alex setAge:12];
[alex print];
return 0;
}
}
Upvotes: 0
Views: 139
Reputation: 39807
person *alex; alex = [person alloc];
is the problem -- you never initialized the object.
person *alex = [[person alloc] init];
is the common way to complete this.
person *alex = [person new];
is a good shortcut (when you're using the standard init
method only).
Upvotes: 1
Reputation: 92384
Class names should start with an uppercase letter by convention, so it should be Person
instead of person
everywhere.
You allocated an instance of the object via [person alloc]
(again, should be [Person alloc]
) but you haven't initialized it. You need to call an initializer, as in [[Person alloc] init]
. (In this specific case, it's not strictly necessary but please always do it nevertheless).
Apart from that, the program works. I get this in the debug console:
2013-10-19 15:20:10.757 Test[13551:303] You are 12 years old!
Program ended with exit code: 0
Upvotes: 2
Reputation: 2823
First off you need to initialize your object.
person *alex = [[person alloc] init];
Upvotes: 0