Here are 2 methods to assign property in Objective-C :
METHOD 1
// in header
@interface Book : NSObject {
NSString *_title;
}
@property (nonatomic, retain) NSString *title;
// in implementation
@implementation Book
@synthesize title = _title;
METHOD 2
// in header
@interface Book : NSObject {
NSString *title;
}
@property (nonatomic, retain) NSString *title;
// in implementation
@implementation Book
@synthesize title;
What are the difference? I use Method 1 recently, as more tutorials recommend Method 1, but nobody explains why.
The difference is the names. In #2 the property and instance field have the same name. In #1 they have different names.
The advantage to #1 is that it’s difficult to accidentally reference the property when you mean the instance field or vice-versa. Referencing the wrong one can lead to having a object retained twice or not retained at all.
The advantage to #2 is that it’s marginally simpler, and it works fine if you’re careful and a bit formal in your use of things.
[And, I see, one flavor specifies
assignand the otherretain, which is a whole different lecture. You’d not normally useassignwith an object pointer.]