objective-c 内存管理和 performSelectorInBackground:
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/873200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Memory management and performSelectorInBackground:
提问by lawrence
Which is right? This:
哪个是对的?这个:
NSArray* foo = [[NSArray alloc] initWithObjects:@"a", @"b", nil];
[bar performSelectorInBackground:@selector(baz:) withObject:foo];
- (void)baz:(NSArray*)foo {
...
[foo release];
}
Or:
或者:
NSArray* foo = [[[NSArray alloc] initWithObjects:@"a", @"b", nil] autorelease];
[bar performSelectorInBackground:@selector(baz:) withObject:foo];
- (void)baz:(NSArray*)foo {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
...
[pool release];
}
I know the first one works, but Clang complains about it, so I wonder if there's a better pattern to use.
我知道第一个有效,但是 Clang 抱怨它,所以我想知道是否有更好的模式可以使用。
I would "just try out" the 2nd one, but with autoreleasing, who knows whether the absence of EXC_BAD_ACCESSmeans that you're doing it right or that you just got lucky...
我会“尝试”第二个,但是通过自动发布,谁知道没有EXC_BAD_ACCESS意味着你做得对还是你只是幸运......
回答by Teemu Kurppa
First is wrong.
首先是错误的。
performSelectorInBackground:withObject: retains both bar and foo until task is performed. Thus, you should autorelease foo when you create it and let performSelectorInBackground:withObject take care of the rest. See documentation
performSelectorInBackground:withObject: 保留 bar 和 foo 直到任务执行。因此,您应该在创建 foo 时自动释放它,并让 performSelectorInBackground:withObject 处理其余的事情。查看文档
Latter is correct because you autorelease foo when you create it. Autorelease pool that you create inside baz has nothing do with correctness of foo's memory management. That autorelease pool is needed for autoreleased objects insidepool allocation and release in baz, it doesn't touch foo's retain count at all.
后者是正确的,因为您在创建它时会自动释放 foo。您在 baz 中创建的自动释放池与 foo 内存管理的正确性无关。需要对自动释放对象的自动释放池里面的巴兹池的分配和释放,它不触及Foo的保留计数的。
回答by Duncan Babbage
The correct approach now would in fact be to do:
现在正确的方法实际上是这样做:
NSArray* foo = [[[NSArray alloc] initWithObjects:@"a", @"b", nil] autorelease];
[bar performSelectorInBackground:@selector(baz:) withObject:foo];
- (void)baz:(NSArray*)foo {
@autoreleasepool {
...
}
}

