Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

JonnyThunder

macrumors member
Original poster
Aug 16, 2008
67
0
Hello,

I'm new to writing in Objective-C (as of yesterday) and am for the first time practicing writing classes. I've got this bit of code...

Code:
#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    int age;
}

- (void) setAge: (int) age;

- (void) showit;

@end   // end of Person (interface)


@implementation Person

- (void) setAge: (int) a
{
    age = a;
}

- (void) showit
{
    NSLog (@"The age for this person is %d", age);
}

@end   // end of Person (implementation)



int main (int argc, const char * argv[]) {
	
	id test[1];
	test[0] = [Person new];
	[test[0] setAge: 25];
	[test[0] showit];
	
    return 0;
}

This works fine, displaying what i'd expect. My question is - if I wanted to add a string value to my class, say "Firstname" - how do I go about adding that? I've tried using NSString - but unsure of the format. I expect my book will cover this eventually, but i'm already attempting to write things before that point.

Any help is gratefully received.
JT
 

MrFusion

macrumors 6502a
Jun 8, 2005
613
0
West-Europe
Code:
#import <Foundation/Foundation.h>

@interface Person : NSObject
{
 NSString *name;
    int age;
}

-(NSString *) name;
-(void) setName:(NSString *) value;
- (void) setAge: (int) age;

- (void) showit;

@end   // end of Person (interface)


@implementation Person
-(void) dealloc{
 [name release];
 [super dealloc];
}

-(NSString *) name {
return name;
}
-(void) setName:(NSString *) value {
 [name release];
 name = value;
 [name retain];
}
- (void) setAge: (int) a
{
    age = a;
}

- (void) showit
{
    NSLog (@"The age for this person is %d", age);
}

@end   // end of Person (implementation)



int main (int argc, const char * argv[]) {
	
	id test[1];
	test[0] = [Person new];
	[test[0] setAge: 25];
	[test[0] showit];
	
    return 0;
}
 

Mac Player

macrumors regular
Jan 19, 2006
225
0
Code:
-(void) setName:(NSString *) value {
 [name release];
 name = value;
 [name retain];
}

better be

Code:
-(void) setName:(NSString *) value {
 [value retain];
 [name release];
 name = value;
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.