gpt4 book ai didi

objective-c - 我需要在 dealloc 中释放吗?

转载 作者:搜寻专家 更新时间:2023-10-30 19:52:22 25 4
gpt4 key购买 nike

在我为 iPhone 开发人员学习的书中,他们利用使用 Interface Builder 的 IBOutlet 实例。一个例子是 UIButton。所以他们在结构中添加了这样的东西:

 IBOutlet UIButton *whateverButton;

然后他们在 .h 中为每个这些添加一个 @property,在 .m 中添加一个 @synthesize

然后他们在 .m 的 dealloc 中包含一个 release。两个问题:

  1. 是否需要发布?不是所有属性都已经自动处理了吗?
  2. 我如何检查引用计数以了解发生了什么,以便进行调试...?

最佳答案

Is the release necessary? Aren't all properties already handled automatically?

如果属性(property)被保留,释放是必要的。当你声明一个 @property@synthesize 时,你得到的只是访问器,dealloc 中没有特殊的自动行为。

此外,IBOutlet 并没有什么神奇之处——它只是一个标记,供 Interface Builder 查看您希望在 IB 中显示哪些属性。它只是一个空宏,按住 Cmd 并单击 IBOutlet 关键字以查看其定义:

#ifndef IBOutlet
#define IBOutlet
#endif

扩展为 void 的 IBAction 也是如此。

How can I check the ref count to see what's happening, for debug purposes...?

当我需要调试内存管理时,我通常只是简单地在 dealloc 方法中设置一个断点或在那里记录一个字符串。记录对象的 retainCount 也很有帮助,因为调用可能会对它产生可疑的影响。


了解 @synthesize 指令如何创建访问器也可能有所帮助。当您声明保留的@property 并要求编译器@synthesize 它们时,您会得到如下内容:

@property(retain) NSString *foo;
@synthesize foo;

- (void) foo {
return foo;
}

- (void) setFoo: (NSString*) newFoo {
// Try to think what would happen if this condition wasn’t
// here and somebody called [anObject setFoo:anObject.foo].
if (newFoo == foo)
return;
[foo release];
foo = [newFoo retain];
}

这不完全是事实,但已经足够接近了。现在应该更清楚为什么要在 dealloc 中释放了。

关于objective-c - 我需要在 dealloc 中释放吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2357518/

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