iphone - @property/@synthesize 问题

标签 iphone objective-c memory-management properties synthesizer

我正在浏览所有关于内存管理的文档,但我对某些事情有点困惑。

当您使用@property 时,它会为对象创建 getter/setter:

.h: @property (retain, nonatomic) NSString *myString

.m: @synthesize myString

我明白这一点,但我感到困惑的是 self.我在不同的博客和书籍中看到了不同的语法。我见过:

myString = [NSString alloc] initWithString:@"Hi there"];

self.myString = [NSString alloc] initWithString:@"Hi there"];

然后在 dealloc 中我看到:

self.myString = nil;

[myString release];

self.myString = nil;
[myString release];

在这个网站上,有人说使用 self 会增加保留计数?是真的吗,我在任何地方都没有看到过。

提供的自动 getter/setter 会自动释放吗?

做这一切的正确方法是什么?

谢谢!

最佳答案

如果您没有使用点语法,那么您就没有使用任何 setter 或 getter。

接下来是,这取决于属性的声明方式。

让我们假设这样的事情:

@property (nonatomic, retain) Article *article;
...
@synthesize article;

分配一些东西给文章

self.article = [[Article alloc] init];

将过度保留 alloc/init 返回的实例并导致泄漏。这是因为 article 的 setter 会保留它并会为您释放任何以前的实例。

因此您可以将其重写为:

self.article = [[[Article alloc] init] autorelease];

这样做

article = [[Article alloc] init]; 

也可以,但可能涉及泄漏,因为文章可能已经包含对实例的引用。因此需要事先释放值:

[article release];
article = [[Article alloc] init]; 

释放内存可以用

[article release];

或与

self.article = nil;

第一个确实直接访问该字段,不涉及 setter/getter。第二个使用 setter 将 nil 设置为该字段。如果在将其设置为 nil 之前有一个实例,它将释放当前实例。

这个结构

self.myString = nil; 
[myString release];

太多了,它实际上将 release 发送到 nil,这是无害但也没有必要的。

您只需在脑子里想出使用点语法的帽子就是使用访问器方法:

self.article = newArticle
// is
[self setArticle:newArticle];

myArticle = self.article;
// is
myArticle = [self article];

一些阅读建议,所有苹果官方文档:

Objective-C 编程语言

内存管理编程指南

关于iphone - @property/@synthesize 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5903281/

相关文章:

iphone - 使用核心数据存储绘制的 map 路径

iphone - UIActivityIndi​​cator 未显示在 webview 顶部

iphone - 在通话过程中播放音频文件

c - Arduino伺服结构 "does not name a type"

.net - 如何确定我的 .NET 应用程序中的内存使用情况

iphone - 带有 UIpagecontroller 的 UIActionsheet

objective-c - "unrecognized selector"不存在

iphone - iOS - 如何删除应用程序窗口层次结构中的所有 ViewController?

ios - 以编程方式使用 Autolayout 布局自定义 UITableViewCell

memory-management - 在 VB 中使用 COM 对象时如何正确管理内存?