问题描述
我了解从 iOS 4 开始,现在可以完全不声明 iVar,并允许编译器在您合成属性时自动为您创建它们.但是,我找不到 Apple 提供的有关此功能的任何文档.
I understand that starting with iOS 4, there is now the ability to not declare iVars at all, and allow the compiler to automatically create them for you when you synthesize the property. However, I cannot find any documentation from Apple on this feature.
另外,是否有关于使用 iVar 和属性的最佳实践或 Apple 推荐指南的任何文档?我一直使用这样的属性:
Also, is there any documentation on best practices or Apple recommended guidelines on using iVars and properties? I have always use properties like this:
.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 名称,以确保在需要使用 self.indexPath
时不会使用 indexPath
.但是现在 iOS 支持自动属性,我不需要担心这个.但是,如果我遗漏了 iVar 声明,我应该如何处理在我的 dealloc 中释放它?我被教导在 dealloc 中释放时直接使用 iVar,而不是使用属性方法.如果我在设计时没有 iVar,我可以只调用属性方法吗?
I use the _indexPath instead of indexPath as my iVar name to make sure that I don't ever use indexPath
when I need to use self.indexPath
. But now that iOS supports automatic properties, I don't need to worry about that. However, if I leave out the iVar declaration, how should I handle releasing it in my dealloc? I was taught to use iVars directly when releasing in dealloc, rather than using the property methods. If I don't have an iVar at design-time, can I just call the property method instead?
推荐答案
我经历了许多不同的方法来处理这个问题.我目前的方法是使用dealloc中的属性访问.不这样做的原因(在我看来)太做作了,除非我知道该物业有奇怪的行为.
I've went through many different ways of dealing with this. My current method is to use the property access in dealloc. The reasons not to are too contrived (in my mind) to not do it, except in cases where I know the property has odd behavior.
@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
这篇关于使用 @synthesize 的自动 iVar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!