我们可以重写 Objective C 中的 alloc 和 dealloc 吗?
我知道很少需要重写 alloc
或 dealloc
方法,但如果需要的话,在 iPhone 编程中是否可能?
I know that this is rarely required to override the alloc
or dealloc
methods,but if required is it possible in iPhone programming?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以而且确实应该(如果使用手动内存管理)覆盖
dealloc
以释放您持有的任何资源(不要忘记在完成时调用[super dealloc]
)。覆盖alloc
是可能的,但正如您所说,很少需要。You can and indeed, you should (if using manual memory management) override
dealloc
to release any resources you hold (not forgetting to call[super dealloc]
when finished). Overridingalloc
is possible but, as you say, rarely needed.一般来说,只有当您希望从可用实例池中分配对象,或者可能根据某些外部参数为对象分配可变的存储量时,才会执行覆盖
alloc
。 (在 C++ 中,您可以访问new
参数并根据它们进行分配,但 Objective-C 不允许您访问initXXX
参数。)我从未尝试过任何我怀疑这有点像雷区——你需要研究结构并非常小心。
正如 Adam 所说,如果您的对象保留了任何保留对象,您应该始终(在引用计数环境中)覆盖dealloc。
更新:您可以做一件有趣的事情...在 RedClass 或其超类中,代码如下:
最终结果是,每当您执行
[RedClass alloc]
时,都会生成一个 BlueCLass对象将被返回。 (注意:大概 BlueClass 是 RedClass 的子类,否则在返回对象后不久事情就会变得严重混乱。)并不是说这样做是一个好主意,但这是可能的(而且我不知道任何对于普通用户定义的类来说它不能可靠地工作的情况)。它确实有一些可能的用途。
附加说明:在某些情况下,人们可能想要使用
[self isSubclassOf:[RedClass class]]
而不是==
(尽管这有一些问题)严重的陷阱)。In general, overriding
alloc
is only done when you wish to, eg, allocate an object from a pool of available instances, or perhaps allocate a variable amount of storage for the object based on some external parameter. (In C++ you can access thenew
parameters and allocate based on them, but Objective-C does not give you access to theinitXXX
parameters.)I've never attempted any of this, and I suspect that its a bit of a minefield -- you need to study up on the structures and be pretty careful.
As Adam said, you should ALWAYS (in a reference counted environment) override
dealloc
if there are any retained objects held by your object.Update: An interesting thing you can do ... in RedClass or a superclass of it code something like:
The net result is that whenever you execute
[RedClass alloc]
a BlueCLass object will be returned. (NB: Presumably BlueClass is a subclass of RedClass, or things will get seriously mucked up shortly after the object is returned.)Not saying that it's a good idea to do this, but it's possible (and I don't offhand know of any cases where it wouldn't work reliably for vanilla user-defined classes). And it does have a few possible uses.
Additional note: In some cases one might want to use
[self isSubclassOf:[RedClass class]]
rather than==
(though that has some serious pitfalls).