【发布时间】:2009-06-17 02:34:29
【问题描述】:
我正在学习 Objective-C,我正在尝试了解内存管理。我对 C 内存管理相当熟悉,但我试图弄清楚 ObjC 的不同之处。
假设我有一个名为Complex 的类用于保存复数,它有一个方法-(Complex*)add:(Complex*)c; 将传入的复数添加到self(假设Complex 是一个可变对象)。
所以我可以这样称呼它:
Complex *c = [[Complex alloc] withReal: -3.0 andImag: -2.4]; // c = -3.0-2.4i
[c add : [[Complex alloc] withReal: 1.0 andImag: 2.0]]; // now c = -2.0-0.4i
在调用add 时创建的临时对象所使用的内存会发生什么变化?我认为这是内存泄漏;这是正确的代码吗?
Complex *c = [[Complex alloc] withReal: -3.0 andImag: -2.4]; // c = -3.0-2.4i
Complex *b = [[Complex alloc] withReal: 1.0 andImag: 2.0]; // b = 1+2i
[c add : b]; // now c = -2.0-0.4i
[b release];
额外的菜鸟问题:Objective-C 2.0 GC 会处理这种情况吗?
【问题讨论】:
标签: objective-c memory-management memory-leaks