gpt4 book ai didi

Objective-C 访问器方法和自动释放的使用

转载 作者:行者123 更新时间:2023-12-02 07:49:22 24 4
gpt4 key购买 nike

我一直在阅读有关内存管理的苹果文档,现在对推荐的访问器实现有点困惑。 Apple 引用了 3 种实现访问器的方法。

技巧一

我复制了第一种技术的代码,它反射(reflect)了:“Getter 在返回值之前保留并自动释放值;setter 释放旧值并保留(或复制)新值。”第一种技术据称更加稳健,但在频繁调用 getter 时会受到性能损失。

- (NSString*) title {
return [[title retain] autorelease];
}

- (void) setTitle: (NSString*) newTitle {
if (title != newTitle) {
[title release];
title = [newTitle retain]; // Or copy, depending on your needs.
}
}

跳过技巧 2

技巧三

第三种技术更适合频繁调用的 setter 和 getter。这也是我一直遵循的方法。

- (NSString*) title {
return title;
}

- (void) setTitle: (NSString*) newTitle {
if (newTitle != title) {
[title release];
title = [newTitle retain]; // Or copy, depending on your needs.
}
}

我的问题是:

  1. (技术 1)setter 首先释放现有值,即使它没有指向任何东西。这会向 nil 发送一条消息,我知道 Objective-C 支持它,但看起来仍然很奇怪。我的理解正确吗?

  2. (技术 1)为什么 retain 会堆叠在 autorelease 中?

  3. (技巧 1)是否期望使用 getter 的调用者在使用完对象后调用 release?

Apple 开发人员文档页面位于:Memory Management Programming Guide - Accessor Methods

最佳答案

(Technique 1) The setter first releases the existing value even if it doesn't point to anything. This would send a message to nil which I understand is supported in Objective-C but still looks odd. Am I understanding this correctly?

是的。发送给 nil 的消息无关紧要。

(Technique 1) Why is the retain stacked inside an autorelease?

这保证了以下内容不会中断:

x = [foo title];
[foo setTitle: @"bar"];
[x length]; // x has been released, possibly, if -title didn't retain/autorelease

(Technique 1) Is the caller whom uses the getter expected to call release after they're done with the object?

没有。


关于Objective-C 访问器方法和自动释放的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4665393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com