Question

I'm currently learning Obj-C for the purpose of iOS programming, but there are some concepts that I am confused about. Specifically, the getter and setter accessors.

I'm reading several different things about them - some are saying they are automatically create when you use @property and there's no need to set them manually, others are saying you need to use @synthesize.

Please see the comments on the code below. I'm confused with what I need to actually manually code, and the proper way to call the method.

// SomeClass.h    
#import <Foundation/Foundation.h>

@interface SomeClass : NSObject

@property (nonatomic, strong) NSString *firstName;

-(NSString *) firstName;

@end


// SomeClass.m

#import "SomeClass.h"

@implementation SomeClass

// DO I NEED THE CODE BELOW OR ARE THESE AUTO-CREATED?
// ****************************************************
-(NSString *) firstName {
    return _firstName;
}

-(void) setFirstname:(NSString *) newValue {
    _firstName = newValue;
}
// ****************************************************

@end


int main () {

  @autoreleasepool {

    SomeClass *aClass = [[SomeClass alloc] init];

    // How would you set the first name?

    aClass.firstName = @"Richard";    //Does this call setFirstName?

    // OR

    [aClass setFirstName:@"Richard"];

  }



  return 0;
}
Was it helpful?

Solution

Some of the things you are reading are old information. @synthesize used to be required (and still can be used), but it is automatically added for you now during compilation (and you should generally use that option).

You don't need -(NSString *) firstName; in the @interface, because the @property definition is already defining that.

// DO I NEED THE CODE BELOW OR ARE THESE AUTO-CREATED?

No, you don't need it, it is auto-generated for you. You would only implement the methods yourself if you wanted to do something special. Usually the auto-generated versions are great because you specify how the methods should be implemented in the @property definition (nonatomic, strong) and that it taken care of for you. If you implement the methods yourself then you are subverting that (so the @property definition could become a lie...).

aClass.firstName = @"Richard"; //Does this call setFirstName?

Yes it does. The compiler actually converts it into:

[aClass setFirstName:@"Richard"];

for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top