内存管理和performSelectorInBackground: [英] Memory management and performSelectorInBackground:

查看:116
本文介绍了内存管理和performSelectorInBackground:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个是对的?这:

NSArray* foo = [[NSArray alloc] initWithObjects:@"a", @"b", nil];
[bar performSelectorInBackground:@selector(baz:) withObject:foo];

- (void)baz:(NSArray*)foo {
    ...
    [foo release];
}

或者:

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];
}

我知道第一个有效,但Clang抱怨它,所以我想知道如果有更好的模式可供使用。

I know the first one works, but Clang complains about it, so I wonder if there's a better pattern to use.

我会尝试第二个,但是有了自动释放,谁知道是否缺少 EXC_BAD_ACCESS 意味着你做得对或者你很幸运...

I would "just try out" the 2nd one, but with autoreleasing, who knows whether the absence of EXC_BAD_ACCESS means that you're doing it right or that you just got lucky...

推荐答案

首先是错的。

performSelectorInBackground:withObject:保留bar和foo,直到执行任务。因此,您应该在创建它时自动释放foo,并让performSelectorInBackground:withObject处理其余的事情。请参阅文档

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

后者是正确的,因为您在创建时自动释放foo。您在baz中创建的自动释放池与foo的内存管理的正确性无关。自动释放的对象需要自动释放的对象里面的池分配和baz中的释放,它根本不会触及foo的保留计数。

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 inside pool allocation and release in baz, it doesn't touch foo's retain count at all.

这篇关于内存管理和performSelectorInBackground:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆