使用@synthesize自动iVars [英] Automatic iVars with @synthesize

查看:106
本文介绍了使用@synthesize自动iVars的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,从iOS 4开始,现在可以根本不声明iVars,并允许编译器在您合成属性时自动为您创建它们。但是,我找不到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.

此外,是否有关于使用iVars和属性的最佳实践或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中释放时直接使用iVars,而不是使用属性方法。如果我在设计时没有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自动iVars的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆