How @property works in Objective C

The goal of the @property directive is to configure how an object can be exposed. If you intend to use a variable inside the class and do not need to expose it to outside classes, then you do not need to define a property for it. Properties are basically the accessor methods.

Its all about encapsulation. Properties and its belongings like strong, weak, assign etc. are here to help in encapsulating objects and its value.

Without properties also one can pass objects but in a well-designed object-oriented program, it’s not advisable to directly access the value of an object.

Code snippet for passing raw object which is not advised to be used:

@interface LoginViewController : UIViewController{
//Declare public variable without declaring @property
@public NSString* username;
}
@end
@implementation ViewController

– (void)viewDidLoad {
[super viewDidLoad];

LoginViewController loginViewController = [[LoginViewController alloc]init];

//Access the variable here.
loginViewController->username = @”Cocoa-juice”;

OR

(*loginViewController).username = @”Cocoa-juice”;

}

@end
Prior to the introduction of properties, methods were required to perform the work of a property but that require the similar code to be written in multiple places. So @property does the job elegantly under the hood.

What it does under the hood?

  • It declares accessor methods (getter and setter) but it doesn’t not define (Lets be clear).
  • Accessor methods are defined by @synthesize directive. Apple developer link for this statement can be verified.
  • Though Objective-C properties are synthesised by default when not explicitly implemented from Xcode 4.4 (LLVM Compiler 4.0) onwards.
  • Use of the @synthesize statement in a class’s implementation block is to tell the compiler to create method definition that matches the specification you gave in the @property declaration.

@property (retain, nonatomic) NSString* name;

Generates below code:

-(NSString*)name;
-(void)setName:(NSString*)userName;


@synthesize name;

Generates below code:
-(NSString*)name{
return _name;

}

-(void)setName:(NSString*)name{
}

example :
self.name = @”cocoa-juice”;
loginViewController.name = self.name;
It eventually calls the accessor methods.

Note: Dot syntax Is a Concise Alternative to accessor method calls which can be used to access the value of the object.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s