Adding string type to a class (noob question)

Discussion in 'Mac Programming' started by JonnyThunder, Aug 16, 2008.

  1. JonnyThunder macrumors member

    Joined:
    Aug 16, 2008
    #1
    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
     
  2. MrFusion macrumors 6502a

    Joined:
    Jun 8, 2005
    Location:
    West-Europe
    #2
    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;
    }
    
     
  3. Mac Player macrumors regular

    Joined:
    Jan 19, 2006
    #3
    Code:
    -(void) setName:(NSString *) value {
     [name release];
     name = value;
     [name retain];
    }
    better be

    Code:
    -(void) setName:(NSString *) value {
     [value retain];
     [name release];
     name = value;
    }
    
     
  4. JonnyThunder thread starter macrumors member

    Joined:
    Aug 16, 2008
    #4
    Thank you for your post. I'll start messing around with it!
     

Share This Page