问题描述
我发现一个Objective-C /可可框架的示例具有以下代码。
I found an example of Objective-C/cocoa framework has the following code.
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Create an array
NSArray *month = [NSArray arrayWithObjects:@ ... nill];
[pool drain];
}
-
Q1:这个(为什么我需要有NSAutoreleasePool代码?)?在
NSAutoreleasePool
和池消耗
块之间发生了什么魔法?我看到我不需要发布* month
。是因为它在NSAutoreleasePool
和pool drain
块中吗?Q1 : What's the magic behind this (Why do I need to have the NSAutoreleasePool code?)? What magic is happening between the
NSAutoreleasePool
andpool drain
block? I see I don't need to release*month
myself. Is this because it's inside theNSAutoreleasePool
andpool drain
block?Q2:使用Xcode,我已经得到了main()函数。在这种情况下,如何使用
NSAutoreleasePool
和池流失
?Q2 : With Xcode, I'm already given the main() function. In this case, how can I use the
NSAutoreleasePool
andpool drain
?例如:
int main(int argc, char *argv[]) { //NSAutoreleasePool *pool = [[[NSAutoreleasePool] alloc] init]; return NSApplicationMain(argc, (const char **) argv); }
推荐答案
Q1: NSObject -autorelease实例方法调用NSAutoreleasePool + addObject:类方法。 NSObject实例在当前NSAutoreleasePool实例中合并。和NSAutoreleasePool -drain实例方法调用池实例的释放方法。
Q1: The magic is that NSObject -autorelease instance method calls NSAutoreleasePool +addObject: class method. The NSObject instance is pooled in the current NSAutoreleasePool instance. And NSAutoreleasePool -drain instance method calls release method of pooled instances.
这与Apple和GNUstep的Cocoa实现不完全相同,但是类似。
It is not the exactly same between Cocoa implementation of Apple and GNUstep, but it is similar.
- NSObject.m
- NSAutoreleasePool.m
我不知道为什么月份不会发布,应该通过排水发布。
I'm not sure why month is not released, it should be release by drain.
你可以使用NSAutoreleasePool,无论你想在哪里使用。实例化NSAutoreleasePool意味着当前池将被新实例更改。 drain将返回当前池到上一个实例。
Q2: You can use NSAutoreleasePool wherever you want to use at. Instantiate a NSAutoreleasePool means the current pool will be changed by the new instance. drain will go back the current pool to the previous instance.
除了NSApplicationMain从不返回。它调用exit函数退出应用程序并终止进程。
Besides NSApplicationMain never returns. It calls the exit function to exit the application and terminate the process.
这篇关于NSAutoreleasePool在Objective-C /可可架构中的神奇之处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!