Bil*_*les 1 release objective-c init new-operator alloc
以下是Foundation应用程序中的两段Objective-C代码.这段代码在一个函数中:
[arrayOfObjects addObject:[[TheShape alloc] init]];
NSLog(@"%@", arrayOfObjects); // log verifies "<TheShape..." is in the array
[arrayOfObjects release];
Run Code Online (Sandbox Code Playgroud)
在我的TheShape类中,我有这个dealloc覆盖方法:
- (void)dealloc {
NSLog(@"TheShape dealloc called.");
[super dealloc];
}
Run Code Online (Sandbox Code Playgroud)
虽然我的程序不起作用,但它并不像我期望的那样工作.当[arrayOfObjects release]发送消息时,我希望看到的"TheShape的dealloc ..."字符串出现在日志中.它没有.
Q1:为什么不呢?
所以我挖了一些并简化了一些事情.如果我做一些更简单的事情:
TheShape *aShape = [[TheShape alloc] init];
[aShape release];
Run Code Online (Sandbox Code Playgroud)
调试消息仍未出现在日志中.
Q2:为什么不呢?
但如果我这样做:
TheShape *aShape = [TheShape new];
[aShape release];
Run Code Online (Sandbox Code Playgroud)
调试消息确实出现在日志中.如果我将第一个样本中的alloc/init更改为,则调试消息也会出现在日志中new.
Q3:为什么?
很显然,我失去了一些东西在分配/初始化/释放周期概念(Q的1和2),并在假想的等效new和alloc/init(Q3).任何人都可以指点我的教程,对于像我这样难以思考的事情来解释一下吗?
谢谢,
法案
你有没有机会覆盖+new你的课程?它应该做的完全相同+alloc/-init.
无论如何,你的第一行
[arrayOfObjects addObject:[[TheShape alloc] init]];
Run Code Online (Sandbox Code Playgroud)
正在泄露您的TheShape实例.你应该把它变成
[arrayOfObjects addObject:[[[TheShape alloc] init] autorelease]];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
915 次 |
| 最近记录: |