Backing properties with ivars


#1

I noticed that BNR code examples do not back properties with ivars. For example,

name is used rather than

I’ve read that because the compiler creates an ivar with the same names as the property with @synthesize, directly accessing the property name might happen, which apparently violates the principle of encapsulation. Also, I’ve read that @sythensize may be deprecated in future versions of Objective-c and automatic ivars may be implemented.

Do you back your properties with _ivars? If not, why not? Thanks!


#2

Additional note: According to the Cocoa Guidelines, you should “prefix instance variable names with an underscore (_),”


#3

In the ObjC book, we do back all the properties with ivars – we just don’t prefix them with an underscore.

In future versions of the iOS book we are moving to not declaring the ivars all, but letting them be auto-created and auto-synthesized. Then we will just access them through the accessor methods. I think this is probably the direction that the community is moving, and we try to match what is going on in the community.

If the lack of an underscore bothers you, please feel free to do the exercises with underscored ivars. You should experience very few surprises.


#4

In Xcode 4.5, the @synthesize statement is now optional, and properties are synthesized automatically. Do you think the community will follow? I wonder why Apple is going this direction?

ref: developer.apple.com/library/mac … wXcode.pdf page 11.


#5

With xcode 4.5 @synthesize is no longer required, it is automatic. So in the example below showing a simple label on the screen,

seems to violate the principle of encapsulation because the ivars bare (which are supposed to be private) are being accessed. I’m wondering if programmers are still including the optional @sythnesize in their implementation files.

[code]//
// ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *label;

@end[/code]

[code]//
// ViewController.m
#import “ViewController.h”
@interface ViewController ()
@end
@implementation ViewController
//@synthesize label; //now optional

  • (void)viewDidLoad
    {
    _label.text = @“hello world”;
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    }
    @end[/code]