[英]Automatic iVars with @synthesize
我知道从iOS 4开始,现在可以根本不声明iVars,并允许编译器在您合成属性时自动为您创建它们。 但是,我找不到Apple关于此功能的任何文档。
此外,是否有关于使用iVars和属性的最佳实践或Apple推荐指南的文档? 我总是使用这样的属性:
.h文件
@interface myClass {
NSIndexPath *_indexPath
}
@property(nonatomic, retain) NSIndexPath *indexPath
@end
.m文件
@implementation myClass
@synthesize indexPath = _indexPath;
- (void)dealloc {
[_indexPath release];
}
@end
我使用_indexPath而不是indexPath作为我的iVar名称,以确保在需要使用indexPath
时我不会使用self.indexPath
。 但是现在iOS支持自动属性,我不需要担心。 但是,如果我省略了iVar声明,我应该如何处理在dealloc中释放它? 我被教导在dealloc中释放时直接使用iVars,而不是使用属性方法。 如果我在设计时没有iVar,我可以直接调用属性方法吗?
我经历了很多不同的处理方式。 我目前的方法是在dealloc中使用属性访问。 在我不知道的情况下(在我看来)不要做太多的设法,除非在我知道属性有奇怪行为的情况下。
@interface Class
@property (nonatomic, retain) id prop;
@end
@implementation Class
@synthesize prop;
- (void)dealloc;
{
self.prop = nil;
//[prop release], prop=nil; works as well, even without doing an explicit iVar
[super dealloc];
}
@end
相反,我做了以下事情:
@interface SomeViewController : UIViewController
@property (nonatomic, copy) NSString *someString;
@end
接着
@implementation SomeViewController
@synthesize someString;
- (void)dealloc
{
[someString release], someString = nil;
self.someString = nil; // Needed?
[super dealloc];
}
@end
注意:在某些时候,Apple将启用默认的合成,这将不再需要@synthesize指令。
您可以使用->
符号而不是点直接访问实例变量.
(将调用ivar相应的访问器方法):
。H
@interface myClass {
}
@property(nonatomic, retain) NSIndexPath *indexPath
@end
.M
@implementation myClass
- (void)dealloc {
[self->indexPath release];
self->indexPath = nil; // optional, if you need it
[super dealloc];
}
@end
因此,您将直接访问iVar而不是相应的访问方法,从而获得额外的好处 - 性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.