difference between accessing a property via “propertyname” versus “self.propertyname” in objective-c?

笑着哭i 提交于 2019-12-18 08:55:21

问题


What is the nce between accessing a property via "propertyname" versus "self.propertyname" in objective-c? Can you cover in the answer:

  1. What is best practice?
  2. How do the two approaches affect memory management (retain counts / one's responsibilities for memory management)
  3. Any 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


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/5251600/difference-between-accessing-a-property-via-propertyname-versus-self-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!