Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

iphone - 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:

  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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...