好吧我说我的功能如下:
-(NSNumber *)calculate{
NSNumber *myNum = [[[NSNumber alloc]initWithInt:5] autorelease];
return myNum;
}
myNum何时会被释放?每当我调用compute时,myNum都会被创建并添加到堆栈中吗?
还说我有一个属性:
@property (nonatomic, retain) NSMutableArray *inputsArr;
我把它合成为:
@synthesize inputsArr = _inputsArr;
我在其中一个mu函数的代码中分配并启动它。 我该如何释放这段记忆? CoaCoa内存管理的任何指南...我只能找到真正令人困惑或明显的指南.. 提前致谢
答案 0 :(得分:1)
自动释放池是线程本地堆栈 - 您可以推送它们。当池被销毁时,延迟的release
消息将被发送到对象。
考虑一下:
NSAutoreleasePool * pool = [NSAutoreleasePool new];
NSNumber * n = [NSNumber numberWithDouble:1.0/17.0]; << n is autoreleased
[n self]; << OK!
[pool release]; << n is messaged release
[n self]; << BAM!
所以'何时'真的取决于自动释放池的构建方式 - 但总是可以确保你的对象比本地池更长,所以这绝不是限制:
NSAutoreleasePool * pool = [NSAutoreleasePool new];
NSNumber * n = [NSNumber numberWithDouble:1.0/17.0]; << n is autoreleased
[n self]; << OK!
[n retain];
[pool release]; << n is messaged release
[n self]; << OK!
[n release];
[n self]; << BAM!
以上是你应该依赖的。在一些现实世界的情况下,一个对象可能仍然存在,你期望“BAM!”,但你永远不应该依赖“好吧,它本应该被摧毁,但似乎工作正常”
答案 1 :(得分:1)
NSApplication
类在初始化期间和事件循环内部 - 特别是在其初始化(或sharedApplication
)和run
方法中设置自动释放池(NSAutoreleasePool类的实例)。通常自动释放池在事件循环结束时弹出,但这取决于您或应用程序
如果您要使用大量临时对象(自动释放/来自方便方法),您可能需要考虑创建自己的短期自动释放池以避免临时内存峰值。Autorelease
对象添加到最新的自动释放要创建的池。
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // create your own little autorelease pool
// these objects get added to the autorelease pool you created above
NSNumber *aNumber1 = [NSNumber numberWithFloat:1]; // refcount is 1, you are not owner, will be automatically released
NSNumber *aNumber2 = [NSNumber numberWithFloat:2]; // refcount is 1, you are not owner, will be automatically released
NSNumber *aNumber3 = [NSNumber numberWithFloat:3]; // refcount is 1, you are not owner, will be automatically released
NSNumber *aNumber4 = [NSNumber numberWithFloat:4]; // refcount is 1, you are not owner, will be automatically released
NSNumber *aNumber5 = [NSNumber numberWithFloat:5]; // refcount is 1, you are not owner, will be automatically released
NSNumber *aNumber6 = [NSNumber numberWithFloat:6]; // refcount is 1, you are not owner, will be automatically released
// ... do a bunch of stuff with all objects above.
...
[pool release]; // all objects added to this pool (the ones above) are released