Reputation: 837
I do not quite understand the way of declaring instance variable and property. Can someone explain in detail the difference of the two codes below? In the second method, if I use _name
for instance variable
, is it the same function as the way declaring name
in first code? Thanks!
First Code:
// OrderItem.h
#import <Foundation/Foundation.h>
@interface OrderItem : NSObject
{
@public NSString *name;
}
-(id) initWithItemName: (NSString *) itemName;
@end
// OrderItem.m
#import "OrderItem.h"
@implementation OrderItem
-(id) initWithItemName: (NSString *) itemName {
self = [super init];
if (self) {
name = itemName;
NSLog(@"Initializing OrderItem");
}
return self;
}
@end
Second Code:
// OrderItem.h
#import <Foundation/Foundation.h>
@interface OrderItem : NSObject
@property (strong,nonatomic) NSString *name;
-(id) initWithItemName: (NSString *) itemName;
@end
// OrderItem.m
#import "OrderItem.h"
@implementation OrderItem
-(id) initWithItemName: (NSString *) itemName {
self = [super init];
if (self) {
_name = itemName;
NSLog(@"Initializing OrderItem");
}
return self;
}
@end
Upvotes: 1
Views: 61
Reputation: 380
Properties are public which means that other classes can read and write them (even classes that aren't subclasses of the class that declares the property). In addition to that, properties provide a getter and a setter method (mutator methods). The getter of a property gets called every time you access the property
NSString *aName = self.name;
Whereas the setter is accessed every time you write or assign to a property.
self.name = @"Some name";
Instance variables (or ivars) are, by default, only visible for the class that declares it and its subclasses (also known as being encapsulated by their class). You can change this default behavior when you add the keyword @public to your ivar declaration though.
Upvotes: 1
Reputation: 130172
In the first case you have declared an instance variable (usually called an ivar in Objective-C).
In the second case you have declared a property. A property is a set of two methods, a getter and a setter, usually accessed using dot notation, e.g. self.name
. However, an ivar is automatically synthesized for the property with the name _name
. That instance variable is what you are accessing in your init
.
You can actually change the name of the ivar using @synthesize name = _myName
or not have it at all (if you declare the getter and setter manually, no ivar will be synthesized).
Objective-C properties are a rather complicated topic so don't worry if you don't understand it immediately.
Upvotes: 1