difference between accessing a property via "propertyname" versus "self.propertyname" in objective-c?
What is the nce between accessing a property via "propertyname" versus "self.propertyname" in objective-c? Can you cover in the answer:
- What is best practice?
- How do the two approaches affect memory management (retain counts / one's responsibilities for memory management)
- A开发者_Go百科ny other advantages/disadvantages
The assumption for the scenario could be based on the following:
Header file
@interface AppointmentListController : UITableViewController {
UIFont *uiFont;
}
@property (nonatomic, retain) UIFont *uiFont;
Implementation
- (void)viewDidLoad {
[super viewDidLoad];
uiFont = [UIFont systemFontOfSize:14.0];
//VERSUS
self.uiFont = [UIFont systemFontOfSize:14.0];
thanks
Using propertyname
just accesses the instance variable. You're responsible for doing your own memory management on its contents; no retains or releases are performed for you.
Using self.propertyname
generally uses an accessor. If you're using @synthesize
, the generated accessors will handle memory management as specified in your @property
line (the example you gave uses retain
, so a retain will be performed on setting a new value to self.propertyname
). You can also write your own accessor methods that do management as you like.
A fuller explanation is in the Memory Management Programming Guide. Best practices in this case are generally to use @property
and @synthesize
to handle your variables, then use the self.propertyname
accessors to reduce the memory management burden on yourself. The guide also recommends you avoid implementing custom accessors (i.e. using @property
without @synthesize
).
An additional note - It's not so useful for the iPhone, since there aren't bindings in Cocoa Touch. But if you're using Cocoa, it's useful to note the following:
Key-Value Coding. KVC is a protocol used throughout Cocoa, most notably in bindings. It will look for accessors for your keys first, and only access data directly as a last resort. You can shorten KVC's search and thus speedup data access by implementing accessors.
Also be aware that if you set instance variables directly, in the form of var = value, Key-Value Observing will not notice the change and bound objects will not get the new value.
精彩评论