ARC内存泄漏 [英] ARC memory leaks

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

问题描述

我在配置为使用ARC的项目中遇到与NSMutableArray链接的内存泄漏,我认为应该为你处理这些事情。

I am experiencing memory leaks linked to NSMutableArray's in a project configured to use ARC, which I thought was supposed to handle these things for you.

以下代码是触发NSNumbers的泄漏:

The following code is triggering leaks of NSNumbers:

NSMutableArray *myArray = [[NSMutableArray alloc] init];

NSNumber  *myNumber = [NSNumber numberWithFloat:10];

[myArray addObject:myNumber];

运行最后一行在调试器中给出以下内容:

Running the last line gives the following in the debugger:


objc [1106]:类__NSCFNumber的对象0x765ffe0自动释放,没有池到位 - 只是泄漏 - 在objc_autoreleaseNoPool()上打破调试

objc[1106]: Object 0x765ffe0 of class __NSCFNumber autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug

除此之外,该对象似乎已正确添加到可变数组中,

Aside from that, the object appears to be correctly added to the mutable array,

我做了明显错误的事情吗?

Am I doing something obvious wrong?

注意:项目中有一个我无法使用ARC的类,因此我使用编译器标志-fno-objc-将其从ARC中排除弧。但是,泄漏发生在使用ARC的其他类中。不确定是否相关。

Note: There is one class in the project which I could not get to work with ARC, and so I excluded it from ARC using the compiler flag -fno-objc-arc. However, the leaks are occurring in other classes that are using ARC. Not sure if that is related.

非常感谢你的帮助。

推荐答案

您可能在后台线程上运行此代码,并且没有自动释放池。 ARC有时会为你自动释放对象,如果你正在调用Apple框架,它们可能仍然是非ARC,所以它们肯定可以为你自动释放对象。所以你仍然需要一个自动释放池。

You're probably running this code on a background thread, and don't have an autorelease pool in place. ARC will still autorelease objects for you on occasion, and if you're calling into Apple frameworks, they may still be non-ARC, so they definitely could be autoreleasing objects for you. So you still need an autorelease pool in place.

Cocoa在主线程上为你创建一个自动释放池,但在后台线程上没有为你做任何事情。如果你打算在没有使用 NSOperation 之类的情况下将某些东西放到后台线程上,你会想要将该线程包装在 @autoreleasepool中,如下所示:

Cocoa creates an autorelease pool for you on the main thread, but doesn't do anything for you on background threads. If you're going to kick something off onto a background thread without using NSOperation or something, you'll want to wrap that thread in an @autoreleasepool, like so:

- (void)doSomething {
    [self performSelectorInBackground:@selector(backgroundSomething)];
}

- (void)backgroundSomething {
    @autoreleasepool {
        NSLog(@"Here I am in the background, doing something.");
        myArray = [[NSMutableArray alloc] init];
        // etc.
    }
}

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

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