【发布时间】:2011-01-25 01:40:39
【问题描述】:
这是 Foundation 应用程序中的两段 Objective-C 代码。这段代码在一个函数中:
[arrayOfObjects addObject:[[TheShape alloc] init]];
NSLog(@"%@", arrayOfObjects); // log verifies "<TheShape..." is in the array
[arrayOfObjects release];
在我的 TheShape 类中,我有这个 dealloc 覆盖方法:
- (void)dealloc {
NSLog(@"TheShape dealloc called.");
[super dealloc];
}
虽然我的程序可以正常工作,但它并没有按我预期的方式工作。当发送[arrayOfObjects release] 消息时,我希望看到“TheShape dealloc...”字符串出现在日志中。没有。
Q1:为什么不呢?
所以我挖掘了一下并简化了一些事情。如果我这样做更简单:
TheShape *aShape = [[TheShape alloc] init];
[aShape release];
调试消息仍然没有出现在日志中。
Q2:为什么不呢?
但如果我这样做:
TheShape *aShape = [TheShape new];
[aShape release];
调试消息确实出现在日志中。如果我将第一个示例中的 alloc/init 也更改为 new,调试消息也会出现在日志中。
Q3:为什么?
显然,我在 alloc/init/release 周期(Q 的 1 和 2)以及假定的 new 和 alloc/init(Q3)的等效性中遗漏了一些概念性的东西。任何人都可以向我指出一个教程,该教程可以像我一样对难以思考的事物进行更多解释吗?
谢谢,
比尔
【问题讨论】:
-
TheShape *aShape = [[TheShape alloc] init];和TheShape *aShape = [TheShape new];应该没有区别。
标签: objective-c release new-operator init alloc