Objective-c – @property and setters and getters

objective-cxcode

If I create a @property and synthesize it, and create a getter and setter as well like so:

#import <UIKit/UIKit.h>
{
    NSString * property;
}

@property NSString * property;

--------------------------------

@implementation

@synthesize property = _property

-(void)setProperty(NSString *) property
{
    _property = property;
}

-(NSString *)property
{
    return _property = @"something";
}

Am I correct in assuming that this call

-(NSString *)returnValue
{
    return self.property; // I know that this automatically calls the built in getter function that comes with synthesizing a property, but am I correct in assuming that I have overridden the getter with my getter? Or must I explicitly call my self-defined getter?
}

is the same as this call?

-(NSString *)returnValue
{
    return property; // does this call the getter function or the instance variable?
}

is the same as this call?

-(NSString *)returnValue
{
    return _property; // is this the same as the first example above?
}

Best Solution

There are a number of problems with your code, not least of which is that you've inadvertently defined two different instance variables: property and _property.

Objective-C property syntax is merely shorthand for plain old methods and instance variables. You should start by implementing your example without properties: just use regular instance variables and methods:

@interface MyClass {
    NSString* _myProperty;
}
- (NSString*)myProperty;
- (void)setMyProperty:(NSString*)value;

- (NSString*)someOtherMethod;
@end

@implementation MyClass

- (NSString*)myProperty {
    return [_myProperty stringByAppendingString:@" Tricky."];
}

- (void)setMyProperty:(NSString*)value {
    _myProperty = value; // Assuming ARC is enabled.
}

- (NSString*)someOtherMethod {
    return [self myProperty];
}

@end

To convert this code to use properties, you merely replace the myProperty method declarations with a property declaration.

@interface MyClass {
    NSString* _myProperty;
}
@property (nonatomic, retain) NSString* myProperty

- (NSString*)someOtherMethod;
@end

...

The implementation remains the same, and works the same.

You have the option of synthesizing your property in your implementation, and this allows you to remove the _myProperty instance variable declaration, and the generic property setter:

@interface MyClass
@property (nonatomic, retain) NSString* myProperty;
- (NSString*)someOtherMethod;
@end

@implementation MyClass
@synthesize myProperty = _myProperty; // setter and ivar are created automatically

- (NSString*)myProperty {
    return [_myProperty stringByAppendingString:@" Tricky."];
}

- (NSString*)someOtherMethod {
    return [self myProperty];
}

Each of these examples are identical in how they operate, the property syntax merely shorthand that allows you to write less actual code.

Related Question