在[self-saveContext]之前是否有可能释放测试对象?
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Test" inManagedObjectContext:[self managedObjectContext]];
for (int i = 0; i < 10; i++)
{
Test *test = [[[Test alloc] initWithEntity:entity insertIntoManagedObjectContext:[self managedObjectContext]] autorelease];
test.text = @"Text";
test.index = [NSNumber numberWithInt:i];
}
[self saveContext];
是。但我认为这需要一根线。
任何时候发送一个对象-自动释放,它都会被添加到最高级别的自动释放池中。只要您没有在方法B中或调用堆栈的下游创建任何新的自动释放池,方法A的池就应该是最高级别的池。
表单在这里(嵌套的)自动释放池的范围是什么?
我认为自动释放范围是指自动释放池何时会被耗尽。您可以使用以下语法定义自动释放作用域:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Test" inManagedObjectContext:[self managedObjectContext]];
@autoreleasepool {
for (int i = 0; i < 10; i++)
{
Test *test = [[[Test alloc] initWithEntity:entity insertIntoManagedObjectContext:[self managedObjectContext]] autorelease];
test.text = @"Text";
test.index = [NSNumber numberWithInt:i];
}
[self saveContext];
}
在正常情况下,当执行进入空闲循环时,自动释放池将被耗尽,但这可以在程序中更改。
没有,除非在一些特定的情况下,让我们找出原因。假设这是在主线程上,在调用选择器之前,系统将在函数之前和之后为您创建一个NSAutoreleasePool
。
因此,如果展开时,您的代码看起来是这样的:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Test"
inManagedObjectContext:[self managedObjectContext]];
for (int i = 0; i < 10; i++)
{
Test *test = [[[Test alloc] initWithEntity:entity insertIntoManagedObjectContext:[self managedObjectContext]] autorelease];
test.text = @"Text";
test.index = [NSNumber numberWithInt:i];
}
[self saveContext];
[pool drain];
entity
将在函数退出后立即释放,即在[self saveContext]
之后。如果你选择启用ARC,它可以解决很多这样的问题
警告
请注意,这不是苹果使用的实际代码,池只会在每一帧中耗尽,而不是在每一种方法中耗尽,但当内存不足时,自动释放池会自动耗尽,所以,如果你的设备内存不足,那么理论上,这可能会导致实体提前释放,但如果发生这种情况,你还需要担心其他问题。
还要注意,在处理线程时,您必须创建自己的自动释放池,系统不会为您这样做。这不是您在这里所要做的,但如果确实发生了这种情况,请记住将选择器封装在@autorelease
块中。
简单地说:
如果你自己不玩自动释放池,那么你的所有对象在一个方法、函数或块中都是安全的。