据我所知,从iOS 4开始,现在可以完全不声明iVars,并允许编译器在您合成属性时自动创建它们。但是,我找不到来自Apple的任何关于此功能的文档。
另外,有没有关于使用iVars和属性的最佳实践或苹果推荐的指南的文档?我一直使用这样的属性:
.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,我可以只调用属性方法吗?
发布于 2011-03-18 02:59:10
我经历了许多不同的方式来处理这个问题。我当前的方法是在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发布于 2011-03-18 02:59:54
作为对比,我做了以下工作:
@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指令。
发布于 2011-03-18 02:41:14
您可以使用->符号直接访问实例变量,而不是点. (这将调用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,而不是它对应的访问器方法,从而获得额外的好处--性能。
https://stackoverflow.com/questions/5343475
复制相似问题