首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用@ iVars自动合成

使用@ iVars自动合成
EN

Stack Overflow用户
提问于 2011-03-18 02:23:47
回答 3查看 2K关注 0票数 6

据我所知,从iOS 4开始,现在可以完全不声明iVars,并允许编译器在您合成属性时自动创建它们。但是,我找不到来自Apple的任何关于此功能的文档。

另外,有没有关于使用iVars和属性的最佳实践或苹果推荐的指南的文档?我一直使用这样的属性:

.h文件

代码语言:javascript
复制
@interface myClass {
    NSIndexPath *_indexPath
}

@property(nonatomic, retain) NSIndexPath *indexPath

@end

.m文件

代码语言:javascript
复制
@implementation myClass

@synthesize indexPath = _indexPath;

- (void)dealloc {
    [_indexPath release];
}
@end

我使用_indexPath而不是indexPath作为我的iVar名称,以确保在需要使用indexPath时不会使用self.indexPath。但现在iOS支持自动属性,我不需要担心这一点。但是,如果我省略了iVar声明,我应该如何处理在我的dealloc中释放它?我被教导在dealloc中发布时直接使用iVars,而不是使用属性方法。如果我在设计时没有iVar,我可以只调用属性方法吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-03-18 02:59:10

我经历了许多不同的方式来处理这个问题。我当前的方法是在dealloc中使用属性访问。不这样做的理由(在我看来)是人为的,不能不这样做,除非我知道属性有奇怪的行为。

代码语言:javascript
复制
@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
票数 6
EN

Stack Overflow用户

发布于 2011-03-18 02:59:54

作为对比,我做了以下工作:

代码语言:javascript
复制
@interface SomeViewController : UIViewController

@property (nonatomic, copy) NSString *someString;

@end

然后

代码语言:javascript
复制
@implementation SomeViewController

@synthesize someString;

- (void)dealloc
{
    [someString release], someString = nil;
    self.someString = nil; // Needed?

    [super dealloc];
}

@end

注意:在某些情况下,Apple将启用默认合成,这将不再需要@synthesize指令。

票数 5
EN

Stack Overflow用户

发布于 2011-03-18 02:41:14

您可以使用->符号直接访问实例变量,而不是点. (这将调用ivar的相应访问器方法):

.h

代码语言:javascript
复制
@interface myClass {
}
@property(nonatomic, retain) NSIndexPath *indexPath

@end

.m

代码语言:javascript
复制
@implementation myClass

- (void)dealloc {
    [self->indexPath release];
    self->indexPath = nil; // optional, if you need it

    [super dealloc];
}
@end

因此,您将直接访问iVar,而不是它对应的访问器方法,从而获得额外的好处--性能。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5343475

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档