问题描述
在Objective-C中通过"propertyname"访问属性与"self.propertyname"之间的关系是什么?你能回答答案吗?
What is the nce between accessing a property via "propertyname" versus "self.propertyname" in objective-c? Can you cover in the answer:
- 什么是最佳做法?
- 这两种方法如何影响内存管理(保留计数/一个人的内存管理职责)
- 其他优势/劣势
该场景的假设可能基于以下内容:
The assumption for the scenario could be based on the following:
头文件
@interface AppointmentListController : UITableViewController {
UIFont *uiFont;
}
@property (nonatomic, retain) UIFont *uiFont;
实施
- (void)viewDidLoad {
[super viewDidLoad];
uiFont = [UIFont systemFontOfSize:14.0];
//VERSUS
self.uiFont = [UIFont systemFontOfSize:14.0];
谢谢
推荐答案
使用propertyname
仅访问实例变量.您有责任对其内容进行自己的内存管理;没有为您执行保留或释放.
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.
使用self.propertyname
通常使用访问器.如果您使用的是@synthesize
,则生成的访问器将按照您在@property
行中指定的方式处理内存管理(您给出的示例使用retain
,因此将新值设置为self.propertyname
时将执行保留). .您还可以编写自己的访问器方法,以根据需要进行管理.
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.
更完整的解释在《内存管理编程指南》 .这种情况下的最佳实践通常是使用@property
和@synthesize
处理变量,然后使用self.propertyname
访问器来减轻您自己的内存管理负担.该指南还建议您避免实施自定义访问器(即,使用@property
而不使用@synthesize
).
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
).
这篇关于通过“属性名称"访问属性之间的区别相对于"self.propertyname"在目标C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!