这是 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)的等效性中遗漏了一些概念性的东西。任何人都可以向我指出一个教程,它可以像我一样为难以思考的人解释更多的东西吗?
谢谢,
账单