cheznead
cheznead

Reputation: 2809

If I write an @synthesize statement, will I get ivar with same name as property and without the underscore?

Just a per the question title, I am aware that if I were to leave out the @synthesize statement I would get an ivar back with the same name of the property and a preceding underscore. So does it follow that if I manually write the @synthesize in a statement I will instead get the ivar with the same name as the property, but without the underscore?

Secondly, as a related question, would you generally advise to have an underscore fronting your ivar.. how should I think about best practice here?

Thanks a lot for any help.

Upvotes: 2

Views: 85

Answers (2)

matt
matt

Reputation: 535944

if I manually write the @synthesize in a statement I will instead get the ivar with the same name as the property, but without the underscore

Yes, you will (although there is a fuller form of @synthesize that lets you state the name that you want).

how should I think about best practice here

Underscore is best practice; that is why it is what you get automatically when you declare a property. That way, you prevent accidental overshadowing. If they both have the same name, for example myVar, then you can say self.myVar or myVar and they are completely different things, which is an invitation to trouble.

Upvotes: 4

Rufel
Rufel

Reputation: 2660

Indeed, if you simply write @synthesize myVar, you will get an iVar set up as myVar. If you want another name, you can go with @synthesize myVar = _myVar. Keep in mind that since Xcode 4.4 auto-synthesize all properties defined in your public class interface, so if you get something like:

@interface TestViewController : UIViewController
@property (nonatomic) BOOL someBoolean;
@end

You will automatically have access to an iVar _someBoolean.

A good practice is to use a combination of public interface properties (when you need subclass or callers to give values or objects to your class) and private interface properties for your own needs:

Example:

// TestViewController.h
@interface TestViewController : UIViewController
@property (nonatomic) BOOL someBoolean;
@property (nonatomic) SomeClass *someClassObject;
@end

// TestViewController.m
@interface TestViewController()
@property (nonatomic) NSString someString;
@end

@implementation TestViewController
- (instancetype)init
{
    if (self = [super init]) {
        // Properties access by iVars
        _someBoolean = YES;
        _someString = @"Test";

        // Properties access
        self.someBoolean = YES;
        self.someString = @"Test";

    }
    return self;
}
@end

The difference between accessing a property directly or by its iVar is that for the former, the setter of that property is executed (if you implemented one).

Upvotes: 3

Related Questions